'Using sed to replace tab with spaces

I'm trying to replace the tab with 4 spaces, using sed, but it is not working.

Here is my code:

sed -i '{s/\t/ \{4\}/g}' filename

Any suggestion is appreciate.



Solution 1:[1]

In sed replacement is not supposed to be a regex, so use:

sed -i.bak $'s/\t/    /g' filename

On gnu-sed even this will work:

sed -i.bak 's/\t/    /g' filename

Solution 2:[2]

There is already an accepted answer but it does hardcoded basic tab expansion, while tabs have a variable width suitable for alignment, which is not taken into account in the previous answer. For example:

12\tabcd
1234\tabcd

should expand to the correctly aligned:

12      abcd
1234    abcd

but the given sed command will incorrectly expand to this misaligned output:

% printf "12\tabcd\n1234\tabcd\n" | sed 's/\t/        /g'
12        abcd
1234        abcd

The correct way to do it is to use the standard command expand, it's installed on all systems.

% printf "12\tabcd\n1234\tabcd\n" | expand     
12      abcd
1234    abcd

If you want to use tabstops of size 4, pass -t 4.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 anubhava
Solution 2