How To Use Linux Tr Command With Examples

February 22, 2011 | By
| Reply More

Linux Tr command

The tr command is used in Linux for translating characters. The tr command utility needs two sets of characters. It replaces occurrences of the characters in the first set with corresponding character from the second set. For example, tr command can be used to change small letters to capital letters and likewise.

When the strings are of the same length, then the corresponding character in the set2 is substituted for the occurrence of each character in set1. If set1 is longer than set2, then tr command will assign the last character of set2 to each of the unspecified positions past the end of the specified string.

Few examples to familiarise Linux tr command.

Syntax:

tr [options] “set1" “set2"

echo something | tr "set1" "set2"

tr "set1" "set2" < input.txt

tr "set1" "set2" << input.txt > output.txt

Example For Linux tr command usage.

Translate the word ‘welcome’ to upper-case:

[root@localhost ~]# echo "welcome" | tr [:lower:] [:upper:]
WELCOME
[root@localhost ~]#

[root@localhost ~]# echo "welcome" | tr "a-z" "A-Z"
WELCOME
[root@localhost ~]#

Some tr command options available

-d option removes the character that has been specified:

[root@localhost ~]# echo "Welcome aagg to Linux dd" | tr -d agd
Welcome to Linux
[root@localhost ~]#

-s option converts each sequence of repeated newlines to a single newline, i.e. replace multiple spaces.

Below command will list all the users listed in the access log and then sort them alphabetically.

#cat /var/log/squid/access.log | tr -s ' ' | cut -d ' ' -f 13 |sort |uniq

Filed Under : HOWTOS, LINUX COMMANDS, LINUX HOWTO

Tagged With :

Free Linux Ebook to Download

Leave a Reply

Commenting Policy:
Promotion of your products ? Comment gets deleted.
All comments are subject to moderation.