Sunday, July 26, 2009

Eight Ways to Convert Tabs to Spaces

A collection of various ways to convert tabs to spaces in Unix/Linux/OS X with standard programs and utilities.
#1 expand/unexpand utilities
expand < input.txt > output.txt

#2 Sed
sed 's/\t/ /g' < input.txt > output.txt

#3 Awk
awk '{ gsub(/\t/, "  "); print }' < input.txt > output.txt

#4 Perl
perl -pe 's/\t/  /g' < input.txt > output.txt

#5 Ruby
ruby -pe '$_.gsub!(/\t/, "  ")' < input.txt > output.txt

#6a Vim editor
:set expandtab
:%retab! 

#6b Vim editor
:%s/\t/  /g

#7 Emacs editor
Set 'indent-tabs-mode' to nil to have tabs automatically converted to spaces.
To convert a region, "M-x untabify" will change tabs to spaces and "M-x tabify" will do the inverse.

#8 cut
cut -f1- --output-delimiter='  ' < input.txt > output.txt

6 comments:

Anonymous said...

and how to do the reverse? space to tab?

Anonymous said...

sed 's/troll/fail/g'

sswam said...

#1 is the way to go

Anonymous said...

Thank you so much!

Anonymous said...

expand source file > destfile

worked like a charm!

Romulus said...

These are fine if you only ever use tabs in their full size as indentation. But if you're using tabs to align output columns (their original intended purpose), only expand(1) will work.

For example if you do:
`abc\tdef`
`a\tbcdef`
with most of these you will get
`abc def`
`a bcdef`
whereas with expand(1) you will get
`abc def`
`a bcdef`