Linux provides various command-line tools to work with text files, expand is one of them. It allows us to replace tabs in a file with spaces. You may have a situation where you have a file that contains many tabs and you want to replace them with spaces. 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 expand command along with some examples.
The syntax of the expand command
The syntax of how to use expand command on Linux is given below.
expand [Option] filename
You can find the options on the expand command’s man page. If no filename is passed as the argument then the command will read from standard input.
How to convert tabs into spaces using expand command
The most basic use of the expand command is to convert the tabs of a file to spaces. You can use the following command to convert tabs into spaces –
Here all the tabs in file1.txt will be replaced by spaces. If you want to replace tabs in multiple files then simply pass the file names separated by spaces as the argument to expand command.
How to convert only initial tabs into spaces
The initial tabs are those that proceed lines to convert these tabs into space you need to use the option
-i with the expand command. It will leave those tabs that appear after non-blanks.
Now see the command below –
expand -i file1.txt
How to tweak the number of spaces using expand command
By default expand command converts tabs into the corresponding number spaces. You need to use the option
-t with the expand command which requires you to enter the new number of spaces(N) you want the tabs to get converted.
Now see the command which is given below –
expand -t file1.txt
How to display expand command help
To display the expand command help you need to use the long option
--help with the expand command in your terminal. You can see below command –
This will display the options and command usages of the expand 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.