05. Tabs to Spaces & Spaces to Tabs expand, unexpand

There may be times when you have finished up writing code, but need to change tabs to spaces for a file to display consistently among different computers. The expand and unexpand commands help you convert from spaces to tabs and tabs to spaces.

Expand filter

In a pipeline, expand converts tabs to spaces. Using specific options, you can specify a number of parameters.

-i
Skip the tab conversions after non-blanks.
-t
Set the number of spaces to replace each tab. By default, it's set to 8.
$ expand -t 4 sample.xml
# Convert every tab into four spaces
<?xml version="1.0" encoding="UTF-8"?>
<note>    
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Please do not forget me this weekend!</body>
</note>

Unexpand filter

The unexpand filter does the opposite - it converts spaces to tabs.

-a
Convert all blanks.
--first-only
Convert only leading sequences.
-t
Set tabs to be a number of spaces apart. Default is 8.

In this example, assume that each "tab" instance is four spaces.

$ unexpand -t 2 sample.xml
# Convert every two spaces to a tab
<?xml version="1.0" encoding="UTF-8"?>
<note>    
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Please do not forget me this weekend!</body>
</note>

Take your Linux skills to the next level!

How Linux Works

Take your Linux skills to the next level! Try Linux & UNIX

In this completely revised second edition of the perennial best seller How Linux Works, author Brian Ward makes the concepts behind Linux internals accessible to anyone curious about the inner workings of the operating system. Inside, you'll find the kind of knowledge that normally comes from years of experience doing things the hard way.

$ Check price
39.9539.95Amazon 5 logo(114+ reviews)

More Linux & UNIX resources

Aching back from coding all day?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ reviews)

More Back Problems resources

Ad