How to replace multiple spaces by one tab

To convert sequences of more than one space to a tab, but leave individual spaces alone:

sed 's/ \+ /\t/g' inputfile > outputfile

To do this for a number of files:

for inputfile in *
do
    sed 's/ \+ /\t/g' "$inputfile" > tmpfile && mv tmpfile "$inputfile"
done

or

for inputfile in *
do
    sed -i.bak 's/ \+ /\t/g' "$inputfile"
done

or

find . -type f -exec sed -i.bak 's/ \+ /\t/g' {} \;

If your character is multiple tabs you can also use tr -s:

-s, --squeeze-repeats   replace each input sequence of a repeated character
                        that is listed in SET1 with a single occurrence

For example:

my_file.txt | tr -s " "

All white spaces will become one.


You can use sed to replace a number of spaces with a tab.:

Example to replace one-or-more-spaces with one tab:

cat spaced-file | sed 's/ \+/\t/g' > tabbed-file