Replace spaces with tabs in a file using the UNEXPAND command in Linux

Home > Search > Linux commands
  by

The unexpand command can be used to change a file to be separated with tabs instead of spaces, and the expand command can be used to change a file to be separated with spaces instead of tabs. In this example, each word in file 1 is separated by a single space.

[root@server1 ]# cat file1
Hello world
How are you today?

 

The unexpand command with the -t or --tabs option can be used to change a space into a tab. In this example, file1 is not changed because the unexpand command will only convert strings consisting of at least two spaces.

[root@server1 ]# unexpand --tabs=1 file1
Hello world
How are you today?

 

Let's take an example where file2 has words separated by at least 2 spaces.

[root@server1 ]# cat file2
Hello  world
How  are  you  today?

 

The unexpand command with the -t or --tabs option will now place a tab (8 spaces) between each word.

[root@server1 ]# unexpand --tabs=1 new-file1
Hello        world
How        are        you        today?

 

The cat command with the -T or --show-tabs and -e (show line feed) options can be used to be absolutely certain that file1 is delimited with tabs. The ^I character represents a tab and $ represents a line feed.

[root@server1 ]# cat -te file1
Hello^Iworld$
How^Iare^Iyou^Itoday?$

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments