This article provided a comprehensive overview of the Linux 'tr' command, covering its history, usage, common parameters, and use cases. The command is versatile, offering great utility for text manipulation directly in the command line. However, it's essential to note its limitation with multi-byte characters. This guide aimed to help newbies to get started with the 'tr' command and utilize it to increase their Linux command-line productivity.
Instructions
This guide provides a thorough overview of the Linux tr
command. It covers everything from the command's history and when to use it, to detailed instructions on how to operate it and understand its parameters. We also discuss the most common use cases and some tricky skills you can use to enhance your command-line productivity.
History
The tr
command, short for translate, is a UNIX utility that has been around since the creation of the UNIX operating system. Its primary use is for translating or deleting characters.
When and why to use it
tr
command is used in Linux for translating or deleting characters. It's very useful when you need to manipulate the content of text or data directly within the command line.
How to use it
tr
command takes two sets of characters as input and replaces occurrences of the characters in the first set with the corresponding character from the second set. Here is a simple example of changing lower-case letters to upper-case:
$ echo 'hello world' | tr 'a-z' 'A-Z'
HELLO WORLD
The commonly used parameters
The tr
command may seem simple, but it comes with several useful parameters that increase its power and flexibility. Here are a few examples:
d
This parameter is used to delete characters in the SET1, does not need SET2.
$ echo 'hello world' | tr -d 'o'
hell wrld
s
This parameter is used to squeeze or reduce repeated characters in SET2 to single occurrence.
$ echo 'hello world' | tr -s ' '
hello world
Other supported parameters
-c
Complements the set of characters in string1.-C
Complement the set of values in string1.
Most common use cases
Here are the most common use cases for tr
:
- Changing character cases
- Deleting characters
- Squeezing repeating characters
$ echo 'aaabbbaaa' | tr -s 'a'
abbba
The tricky skills
One of the interesting ways to use tr
is to combine it with other commands like sort
and uniq
to count occurrences of unique lines in a text file.
$ cat filename | tr ' ' '\\n' | sort | uniq -c
What needs to be noted
Note that tr
works with single-byte characters only. It does not handle multi-byte characters (like Unicode characters) properly.
Conclusion
The tr
command is a powerful and flexible tool that should be in every Linux user's toolkit. From manipulating text to counting unique lines, tr
offers numerous practical uses to enhance your command-line efficiency.