Skip to Content
Linux Shell Scripting Cookbook - Third Edition
book

Linux Shell Scripting Cookbook - Third Edition

by Clif Flynt, Sarath Lakshman, Shantanu Tushar
May 2017
Beginner
552 pages
28h 47m
English
Packt Publishing
Content preview from Linux Shell Scripting Cookbook - Third Edition

Squeezing characters with tr

The tr command can perform many text-processing tasks. For example, it can remove multiple occurrences of a character in a string. The basic form for this is as follows:

tr -s '[set of characters to be squeezed]' 

If you commonly put two spaces after a period, you'll need to remove extra spaces without removing duplicated letters:

$ echo "GNU is       not     UNIX.  Recursive   right ?" | tr -s ' '
GNU is not UNIX. Recursive right ?

The tr command can also be used to get rid of extra newlines:

$ cat multi_blanks.txt | tr -s '\n'
line 1
line 2
line 3
line 4

In the preceding usage of tr, it removes the extra '\n' characters. Let's use tr in a tricky way to add a given list of numbers from a file, as follows:

$ cat sum.txt ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Linux Shell Scripting - Second Edition

Mastering Linux Shell Scripting - Second Edition

Mokhtar Ebrahim, Andrew Mallett

Publisher Resources

ISBN: 9781785881985