Skip to content

Linux Foundations / Find your way around Linux ยท Step 40 of 63

Lesson: expand and unexpandSwitch
โ† Linux Foundations

Shell and files

expand and unexpand

Learn to convert tabs to spaces and spaces back to tabs.

A tab is one character that moves to the next tab stop, so its width on screen varies. That can make text line up in one editor and not in another. expand and unexpand convert between tabs and spaces.

See the tabs

Tabs and spaces look alike. With GNU cat, -T shows each tab as ^I.

$ printf 'a\tb\n' > tabs.txt
$ cat -T tabs.txt
a^Ib

On other systems, cat -t does a similar job.

expand: tabs to spaces

$ expand tabs.txt
a       b

Tab stops are every 8 columns by default. a fills one column, so the tab becomes 7 spaces.

-t changes the spacing:

$ expand -t 4 tabs.txt
a   b

expand writes to stdout and leaves the original alone. Save the result under a new name:

$ expand -t 4 tabs.txt > spaces.txt

Do not redirect back to the input file, because the shell would empty it first.

unexpand: spaces to tabs

unexpand does the reverse. By default it converts only the blanks at the start of each line.

$ printf '        x        y\n' | unexpand | cat -T
^Ix        y

The leading 8 spaces became a tab. The spaces after x stayed.

Add -a to convert runs of blanks elsewhere in the line too, where they reach a tab stop. A single space before a tab stop is left alone.

You can set the width with -t. In GNU unexpand, using -t also turns on -a; add --first-only if you want leading blanks only.

$ printf '    x\n' | unexpand -t 4 --first-only | cat -T
^Ix

When it matters

Some formats are strict. Recipe lines in a Makefile must begin with a tab by default, while YAML does not allow tabs for indentation. Converting a file with the right tool is quicker than retyping it. Check the result with cat -T before relying on it.

You can experiment in the streams and text lab.

Try it

  1. Run printf '1\t2\t3\n' > t.txt.
  2. Compare cat t.txt, cat -T t.txt and expand -t 2 t.txt.
  3. Run expand t.txt | cat -T. No ^I should remain.
  4. Run expand t.txt | unexpand -a | cat -T.

Check your understanding

expand and unexpand

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.