Bash Shell: Convert Tabs To Spaces In a File

by on March 5, 2010 · 5 comments· last updated at March 5, 2010

How do convert tabs to spaces in a file using a bash shell?

You can use various tools. The expand command converts all tabs to spaces. It preserves backspace characters in the output; they decrement the column count for
tab calculations.

expand input.file > output.file
expand data.txt > output.txt
expand -t 2 data.txt > output.txt

The -t option can be used to set comma separated list of explicit tab positions. You can use the unexpand command convert spaces to tabs. See man page for more info:
man expand
man unexpand



You should follow me on twitter here or grab rss feed to keep track of new changes.

Featured Articles:

{ 5 comments… read them below or add one }

1 Tapas Mallick March 6, 2010 at 3:03 pm

My imput.file looks like:
$ cat input.file
tux Linux
tux Linux
tux Linux
tux Linux
$
But executing expand on the file showing the same format(in STDOUT) as input.file…
$ expand input.file
tux Linux
tux Linux
tux Linux
tux Linux
$
Though I am getting the expected result with “tr” command.
I am using CentOS 5.3(x86_64); Any comment ?

Reply

2 stealth March 9, 2010 at 1:33 pm

You can also use perl:
perl -pi -e ‘s/\t/ /’ file.name

Reply

3 Gen2ly March 10, 2010 at 5:35 am

:retab

for vim.

Reply

4 Tapas Mallick March 17, 2010 at 8:26 am

s are truncated in my posts itself :)

Reply

5 Towo March 14, 2013 at 3:17 pm

expand fails miserably on multibyte characters (i.e. on non-ASCII characters in UTF-8 encoding)
still as of coreutils 8.21 (2013)

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <kbd> <blockquote> <pre> <a href="" title="">

Tagged as: , , , , , , , , , , , , , , , ,

Previous Faq:

Next Faq: