Linux Command Reference ยท Text Processing
Linux expand and unexpand commands
Reference for the Linux expand and unexpand commands: convert tabs to spaces and spaces to tabs, set tab stops, and handle leading whitespace only.
expand replaces tab characters with the spaces needed to reach the next tab stop, so text looks the same everywhere. unexpand does the reverse: it turns runs of spaces into tabs where they line up with tab stops.
They are small but useful when you inherit files with mixed indentation, when a Makefile needs real tabs, or when a tool misaligns columns because it renders tabs differently from your terminal.
expand [OPTION]... [FILE]... unexpand [OPTION]... [FILE]...
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Syntax
expand [-i] [-t N | -t LIST] [FILE]... unexpand [-a] [--first-only] [-t N | -t LIST] [FILE]...
| Option | Command | Description |
|---|---|---|
-t N |
both | Tab stops every N columns (default 8). |
-t N1,N2,... |
both | Explicit tab stop positions; the last number can repeat with /N or +N (GNU). |
-i |
expand | Convert only tabs at the start of a line (initial tabs). |
-a |
unexpand | Convert all runs of spaces, not only leading ones. |
--first-only |
unexpand | Convert only leading blanks (the default without -a). |
Returns: 0 on success, non-zero on error.
Usage notes
- A tab is not a fixed number of spaces. It advances to the next tab stop, so
a<TAB>andabcdefg<TAB>end in the same column.expandcalculates the right number of spaces for each. unexpandonly converts blanks that reach a tab stop; blanks that stop short of one are left as spaces. With-t, GNUunexpandimplies-a.- Backspace moves the column back by one in both tools, which matters for old overstrike text.
- Leading-only conversion is what you want for source code:
expand -iavoids changing tabs inside strings. - Makefiles need real tabs for recipe lines, so never run a Makefile through
expand. - Typical clean-up:
expand -t 4 file > file.newto convert a project to space indentation, then compare withdiff -w. - Alignment of tables: convert tab-separated columns to spaces before pasting into email or chat, because tab widths vary.
- Mixed content: the tools do not understand quoting or languages, so check the result with a diff.
Related
cat,tr,column,sed- Lessons: Viewing text, Text processing recipes