Bash Shell: Convert Tabs To Spaces In a File

Posted on in Categories last updated 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

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

9 comment

  1. 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 ?

    1. That’s because expand expects 2 tabs (=8 charachter spaces) as default tab.
      So it doesn’t a tab in your file.
      The command expand -t1 wil work with your file, as t1 means 4 spaces

  2. expand doesn’t seem to do the right thing.
    Converting tabs to spaces in a piece of content is more than merely translating each tab character to a sequence of space characters. It needs to preserve the alignment of the text. So in this example text (no quotes):
    “Foo\tBar\tBazinga!”
    and with a tab spacing of 3 chars, the result should be (each period corresponds to a white space):
    “Foo…Bar..Bazinga!”
    This way the de-tabbed content would overlay the original content exactly (assuming the same tab setting).

  3. Typo in my example, and not a great example. Let’s try this one instead:
    “Foo\tBars\tBazinga!”
    and with a tab spacing of 4 chars, the result should be (each period corresponds to a white space):
    “Foo.Bars….Bazinga!”

    Note how each tab char was not replaced with 4 spaces.

Leave a Comment