Understanding Linux / UNIX tr command

by Vivek Gite [Last updated: December 23, 2007]

Q. Can you explain the tr command and how to use it under Linux / UNIX like oses?

A. The tr utility copies the given input to produced the output with substitution or deletion of selected characters. tr abbreviated as translate or transliterate. It takes as parameters two sets of characters, and replaces occurrences of the characters in the first set with the corresponding elements from the other set i.e. it is used to translate characters.

It is commonly used in shell scripts and other application.

tr command syntax

tr [options] "set1" "set2"
echo something | tr "set1" "set2"
tr "set1" "set2" < input.txt
tr "set1" "set2" < input.txt > output.txt

How do I use tr command under Linux / UNIX?

Translate the word 'linux' to upper-case:
$ echo 'linux' | tr "[:lower:]" "[:upper:]"
$ echo 'linux' | tr "a-z" "A-Z"
$ echo 'I LovE linuX. one is better Than 2' | tr "a-z" "A-Z"

Output:

LINUX
I LOVE LINUX. ONE IS BETTER THAN 2

Create a list of the words in /path/to/file, one per line, enter:
$ tr -cs "[:alpha:]" "\n" < /path/to/file
Where,

  • -c : Complement the set of characters in string1
  • -s : Replace each input sequence of a repeated character that is listed in SET1 with a single occurrence of that character

Shell scripting example

In the following example you will get confirmation before deleting the file. If the user responds in lower case, the tr command will do nothing, but if the user responds in upper case, the character will be changed to lower case. This will ensure that even if user responds with YES, YeS, YEs etc; script should remove file:

#!/bin/bash
echo -n "Enter file name : "
read myfile
echo -n "Are you sure ( yes or no ) ? "
read confirmation
confirmation="$(echo ${confirmation} | tr 'A-Z' 'a-z')"
if [ "$confirmation" == "yes" ]; then
   [ -f $myfile ] &&  /bin/rm $myfile || echo "Error - file $myfile not found"
else
   : # do nothing
fi

Remove all non-printable characters from myfile.txt
$ tr -cd "[:print:]" < myfile.txt

Remove all two more successive blank spaces from a copy of the text in a file called input.txt and save output to a new file called output.txt
tr -s ' ' ' ' < input.txt > output.txt

The -d option is used to delete every instance of the string (i.e., sequence of characters) specified in set1. For example, the following would remove every instance of the word nameserver from a copy of the text in a file called /etc/resolv.conf and write the output to a file called ns.ipaddress.txt:
tr -d 'nameserver' < /etc/resolv.conf > ns.ipaddress.txt

Recommended readings:

To check the other options that can be used in the tr command, see the tr command man page, enter:
$ man tr

Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our daily email newsletter to make sure you don't miss a single tip/tricks. Subscribe to our weekly newsletter here!

{ 7 comments… read them below or add one }

1 Planet Lowyat 12.23.07 at 3:48 pm

Great tips. Typo error -> prodcued

2 Marko 02.13.08 at 3:08 pm

tr -d ‘nameserver’ ns.ipaddress.txt

I think this would delete the word nameserver, but also all occurrences of characters from set {nameserver}, which could probably create big mess.

Proper command should be:
sed ’s/nameserver//g’ ns.ipaddress.txt

3 Maher 08.23.08 at 11:10 am

can you give scripts for these :
Exercise 1: Write a shell script (named checkfiles.sh) that lists
all text files “*.TXT” in a directory and writes the first line of each text-file to a file called Text_Heads.

Exercise 2: Write a shell script (called words-no.sh) that counts the number of distinct words in a text file given as Argument.

Remark: White space characters are spaces, tabs, form feeds, and new lines. Use the tr, sort, grep. wc.

Exercise 3: Write a shell script (called cleancore.sh) that removes unwanted files from a directory and its subdirectories.
Argument 1 is the directory where to start the search. It defaults to your home directory (If there is no directory by this name).
Argument 2 after the directory is standard file-name that match the files that are to be removed, it defaults is ‘core’.

4 heba 09.01.08 at 11:45 am

How can I get the Exercises solve??

Please help me

5 laoa 09.10.08 at 11:02 am

Is there any way to do the following questions

1. Replace many different chars with one same char

ab(cde)fg -> ab~cde~fg
echo ab(cde)fg | tr “()” “~~”

echo a1234b | tr “[0-9]” “A”
a1234b ### hope aAAAAb
echo a1234b | tr “[0-9]” “AAAA”
aAAA4b
echo a1234b | tr “[0-9]” “AAAAA”
aAAAAb

2. replace one char with two chars

a~b -> a==b

Thanks

6 vivek 09.10.08 at 12:21 pm

laoa,

Avoid shell escape, enter:
echo 'ab(cde)fg' | tr "()" "~~"
OR
echo ab\(cde\fg | tr "()" "~~"

7 pham van hai 11.11.08 at 3:39 pm

please help me
convert file in window into file in linux
I try
cat file_linux | tr -s “\n” “\n\r” ?
but it cannot run

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Tagged as: , , , , , , ,

Previous post: Linux install and configure an AMANDA backup client

Next post: Configure Linux DHCP client ( dhclient ) to persistently look for an IP address lease