Monday, January 9, 2012

Replacing tabs/spaces with expand/unexpand

To replace tabs with spaces in a text file use expand.
To replace spaces with tabs in a text file use unexpand. 


To play a little arround with expand create a small list first:

$ echo -e "1\ta\n2\tb\n3\tc" > tabs.txt

The above command will create a small list with 3 lines and 2 rows seperated by tabs. Then run the first expand command:

$ cat tabs.txt | expand
1       a
2       b
3       c

When you look at the output then you will notice that nothing has changed - which is not quiet right. The tabs were substituted by 8 spaces. You can control the number of spaces by using the -t option:

$ cat tabs.txt | expand -t 3
1  a
2  b
3  c


For unexpand create a new list:

$ echo -e "1       a\n2       b\n3       c" > spaces.txt

Then replace the spaces with tabs:

$ cat spaces.txt | unexpand -a
1       a
2       b
3       c

Again, nothing seems different - which is also not right again. The spaces were substituted by tabs. When you redirect the output to a new file and open it with any editor you will recognize it. Otherwise just use od:

$ cat spaces.txt | unexpand -a | od -c
0000000   1  \t   a  \n   2  \t   b  \n   3  \t   c  \n

For more information about expand and unexpand read the man pages:

$ man expand
$ man unexpand