unexpand command in Linux with Examples
To convert the leading spaces and tabs into tabs, there exists a command line utility called unexpand command. The unexpand command by default converts each space into tabs writing the produced output to the standard output.
Syntax
$unexpand [OPTION]... [FILE]...
where,
- OPTION: Represents the various options or flags available for modifying the behavior of unexpand.
- FILE: Refers to the name of the file on which the command operates.
Using unexpand command
To convert all the space characters into tab characters in the file kt.txt, use unexpand as:
$cat -vet kt.txt
have a nice day$
always try harder$
to achieve better$
/* In the below output $ refers to
the new line feed and ^I refers
to the tab */
$unexpand kt.txt
have^Ia^Inice^Iday$
always^Itry^Iharder$
to^Iachieve^Ibetter$
In order to save the produced output by unexpand command in another file let's say dv.txt use the below syntax:
/* Saving output in file, dv.txt */
$unexpand kt.txt>dv.txt
$cat -vet dv.txt
have^Ia^Inice^Iday$
always^Itry^Iharder$
to^Iachieve^Ibetter$
Key Options for the unexpand command
1. -a, - -all option
This option is used to convert all blanks, instead of just initial blanks (which is by default).
/* This converts all the blanks
also into tabs */
$unexpand -a kt.txt>dv.txt
2. --first-only option
This is used to convert only leading sequences of blanks (overrides -a option).
/* This converts only the leading
sequences of blanks */
$unexpand --first-only kt.txt>dv.txt
3. -t, - -tabs=N option
This set tabs N characters apart instead of the default of 8 (enables -a option).
/* the -t option with numerical value
2 forces to change the spaces
into tabs of only 2 characters */
$unexpand -t2 kt.txt>dv.txt
Other available Options
Option | Description |
---|---|
-t , --tabs=LIST | Uses a comma-separated list of tab positions, enabling the -a option to convert all spaces to tabs. |
--help | Displays a help message with usage information and exits. |
--version | Displays version information of the unexpand command and exits. |
Also see: expand command
Conclusion
The unexpand command in Linux is a simple yet powerful tool for converting spaces to tabs in text files. With its various options, such as -a for converting all spaces, -t for custom tab widths, and --first-only for restricting changes to leading spaces, it offers flexibility in managing text file formatting.