Replace tabs with spaces in Linux

Posted by jason on July 4, 2011, 11:03 a.m.
Tags:

Here's how to replace tabs with spaces in linux. There are 2 ways.

Method 1: the 'expand' command

If you don't mind juggling temporary files around, then the expand command might do:

expand -t 4 -i myfile.txt

This command takes all tabs and converts them into 4 spaces. The problem is that expand sends the result to stdout, and I don't know of an easy way to do the equivalent of "expand -t 4 -i myfile.txt > myfile.txt". Note that that command does not work: it will leave you with an empty mytfile.txt. So that means you need to do something tedious like "expand -t 4 -i myfile.txt > myfile2.txt; rm myfile.txt; mv myfile2.txt myfile.txt". There has to be an easier way, but I don't have time to delve into the intricacies of bash shell scripting to figure it out.

Method 2: the 'sed' command

I prefer this method, because sed lets me modify the existing file. Here's the command:

sed -i 's/<press CTRL+v followed by the TAB key here>/    /g' myfile.txt

0 comments