Linux provides various command-line tools to work with text files, we discussed expand command in a previous article which converts all tabs in a file into spaces.
There exist another utility called unexpand which converts all blanks into the tabs. You may have a situation where you have a file that contains many spaces and you want to replace them with tabs. The task is not so difficult if you have a small file you can do this task manually but what if the file is larger.
In this article, you will learn the usage of the unexpand command along with some examples.
The syntax of the unexpand command
The syntax of using unexpand command on Linux is given below.
unexpand [Option] filename
You can find the options on the unexpand command’s man page. If no filename is passed as the argument then the command will read from standard input.
How to convert blanks into tabs using unexpand command
The most basic use of the unexpand command is to convert the blanks or spaces of a file into tabs. You can use the following command to convert all blanks to tabs –
Replace the file1.txt with your own filename. Here all the blanks in file1.txt will be replaced by tabs. If you want to replace blanks in multiple files then simply pass the file names separated by spaces as the argument to unexpand command.
How to convert only initial or leading spaces into tabs
The initial or leading blanks are those that proceed lines to convert these blanks into tabs you need to use the option
--first-only with the unexpand command. It will leave those blanks or spaces that come in the middle of a line.
Now see the command below –
unexpand --first-only file1.txt
Using option -t with unexapand command
-t sets tabs N character aparts instead of the default 8. It can also take multiple comma-separated inputs.
For example –
unexpand -t 5 file1.txt
or provide multiple input –
unexpand -t 2,3,4 file1.txt
How to display unexpand command help
To display the unexpand command help you need to use the long option
--help with the unexpand command in your terminal. You can see below command –
This will display the options and command usages of the unexpand command in your terminal.
Now try the command with a text file by this way you will be able to use this tool in the correct way. If you have a query on this then write us in the comments below.