Intro To 'unexpand' Command In Linux
2023-06-21 - By Robert Elder
I use the 'unexpand' command to replace spaces with tabs:
unexpand -a file1.txt
Here, I have an 'echo' statement that prints out 8 space characters:
echo -n ' ' | xxd
00000000: 2020 2020 2020 2020
When I pipe these 8 spaces into the 'unexpand' command, they'll be replaced by a single tab character:
echo -n ' ' | unexpand | xxd
00000000: 09 .
Default Behaviour & Initial Non-Blank Characters
Here is another echo statement that prints a sequence of 7 spaces between the letters 'a' and 'b':
echo -e "a b" | xxd
00000000: 6120 2020 2020 2020 620a a b.
By default, the 'unexpand' command does not replace any spaces that appear after the first non-blank character:
echo -e "a b" | unexpand | xxd
00000000: 6120 2020 2020 2020 620a a b.
However, if you add the '-a' flag, these later spaces will be replaced:
echo -e "a b" | unexpand -a | xxd
00000000: 6109 620a a.b.
This default behaviour is different from the 'unexpand's counterpart the 'expand' command.
'unexpand' Does Not Un-do 'expand'
Both the 'expand' and 'unexpand' commands support the '-t' flag to describe tab widths or tab locations. However, it's worth noting that the 'unexpand' command will not perfectly 'undo' the work of the 'expand' command.
For example, if you consider a file called 'living-expenses.txt' with the following contents:
Category Jan Feb Mar
Food $102.78 $97.34 $112.42
Rent $380.00 $380.00 $380.00
Linux Weekly News Subscription $9.00 $9.00 $9.00
Artistic Anime Figurines $1,749.38 $2,109.87 $3,829.48
This use of the 'expand' and 'unexpand' commands illustrates a case that does not reproduce the original file:
expand -t 1,33,43,53,63 living-expenses.txt | unexpand -t 1,33,43,53,63
You can use this 'vim' command to view a comparison of the difference:
vim -d living-expenses.txt <(expand -t 1,33,43,53,63 living-expenses.txt | unexpand -t 1,33,43,53,63)
which looks something like this:
And that's why the 'unexpand' command is my favourite Linux command.
Intro To 'stty' Command In Linux
Published 2023-10-04 |
$1.00 CAD |
Intro To 'nproc' Command In Linux
Published 2023-07-15 |
Intro To 'comm' Command In Linux
Published 2023-09-06 |
How To Force The 'true' Command To Return 'false'
Published 2023-07-09 |
A Surprisingly Common Mistake Involving Wildcards & The Find Command
Published 2020-01-21 |
A Guide to Recording 660FPS Video On A $6 Raspberry Pi Camera
Published 2019-08-01 |
Intro To 'chroot' Command In Linux
Published 2023-06-23 |
Join My Mailing List Privacy Policy |
Why Bother Subscribing?
|