The tr Command in Linux
The tr
command in Linux is a powerful tool used for character translation or deletion. It is a versatile command that can perform a wide range of operations on text data. In this answer, we will explore the different options available in the tr
command and provide examples to help you understand its usage.
Basic Syntax
The basic syntax of the tr
command is as follows:
tr [OPTION] SET1 [SET2]
Here, SET1
and SET2
are the sets of characters that you want to translate or delete.
Available Options
The tr
command offers several options to customize its behavior. Let's explore the most common ones:
-
Character Translation:
-c, --complement
: Complement the set of characters inSET1
.-d, --delete
: Delete characters inSET1
from the input.-s, --squeeze-repeats
: Replace consecutive occurrences of the same character inSET1
with a single occurrence.-t, --truncate-set1
: TruncateSET1
to the length ofSET2
.
-
Character Classification:
[:alnum:]
: Alphanumeric characters.[:alpha:]
: Alphabetic characters.[:digit:]
: Numeric characters.[:lower:]
: Lowercase alphabetic characters.[:upper:]
: Uppercase alphabetic characters.[:space:]
: Whitespace characters (spaces, tabs, newlines, etc.).[:punct:]
: Punctuation characters.
-
Escape Sequences:
\a
: Alert (bell).\b
: Backspace.\f
: Form feed.\n
: Newline.\r
: Carriage return.\t
: Horizontal tab.\v
: Vertical tab.
-
Range Specification:
- You can specify a range of characters using the
-
symbol, e.g.,a-z
orA-Z
.
- You can specify a range of characters using the
Examples
-
Translating Uppercase to Lowercase:
echo "HELLO, WORLD!" | tr "A-Z" "a-z"
Output:
hello, world!
-
Deleting Specific Characters:
echo "Hello, World!" | tr -d "," "!"
Output:
Hello World
-
Squeezing Repeated Characters:
echo "Hello World!" | tr -s " "
Output:
Hello World!
-
Complementing a Set of Characters:
echo "Hello, World!" | tr -c "a-zA-Z" "_"
Output:
_e_l_l_o__W_o_r_l_!_
-
Translating Characters Based on Character Classification:
echo "Hello123, World456!" | tr "[:digit:]" "X"
Output:
HelloXXX, WorldXXX!
By understanding the different options available in the tr
command, you can perform a wide range of text manipulation tasks, such as character translation, deletion, and transformation. The examples provided should give you a good starting point to explore the capabilities of this powerful Linux tool.