Working on the Linux command line requires to learn how to quickly perform some repetitive tasks. One such task that you may find yourself involved in sooner or later is converting blanks to tabs or vice-versa. In this tutorial, we will discuss a command line utility – dubbed unexpand – that’ll be of great help in such situations.
But before we start, it’s worth mentioning that all examples in this article have been tested on an Ubuntu 16.04 LTS machine.
Linux unexpand command
The unexpand command lets you convert spaces into tabs. Following is its syntax:
unexpand [OPTION]… [FILE]…
And here’s how the man page describes it:
Convert blanks in each FILE to tabs, writing to standard output. With no FILE, or when FILE is -, read standard input.
Following are some Q&A-styled examples that should give you a good idea on how the unexpand command works.
Q1. How to use unexpand command?
Suppose you have a file with text containing tabs. Now, for whatever reason, you convert those tabs into spaces using the expand command, and now you want to convert spaces into tabs again, then in this case, you can use the unexpand command.
The tool produces the converted output on stdout. So to save it, you can redirect it to some file. For example:
unexpand file1 > file2
It’s worth mentioning that by default this tool only works on initial blanks. You can use the -a option to tell the utility that you want to convert all spaces/blanks into tabs.
Q2. How to force unexpand convert only initial/leading blanks?
The tool provides an option that forces it to convert only initial blanks or spaces (even if the -a option is present). The option in question is –first-only.
unexpand –first-only -a file1 > file2
Q3. What the -t option does?
Well, the -t option has multiple roles. It accepts either a single number, or a comma-separated list of numbers. When you pass a single number (say ‘n’), the unexpand command makes sure it compresses spaces in the file into tabs every ‘n’ positions.
For example, to make the tool compress blanks into tabs every 3 positions, use this option in the following way:
unexpand -t 3 file1 > file2
On the other hand, if this option is given a command separated list of numbers, the tool places tab stops at those specific positions.
unexpand -t 1,2,3 file1 > file2
Q4. How to make unexpand read input from STDIN?
This is fairly easy – just run the command without any file name as input (use ctrl+D to tell the utility that you’re done).
Here’s what I am talking about:
Depending upon the kind of work you do, the unexpand command could be of great help. In this tutorial, we discussed the majority of the command line option this tool offers. To know more, head to its man page.