Linux/Unix – Translating or Removing Characters with tr

The tr command is an easy way to do simple character translations on the fly. In the following example, new lines are replaced with spaces, so all the files listed from the current directory are output on one line:

$ ls | tr ‘\n’ ‘ ‘

Replace newline characters with spaces


The tr command can be used to replace one character with another, but does not work with strings like sed does. The following command replaces all instances of the lowercase letter f with a capital F.

$ tr f F < myfile.txt

Replace every f in the file with F


You can also use the tr command to simply delete characters. Here are two examples:

$ ls | tr -d ‘\n’


Delete new lines (resulting in one line)

$ tr -d f < myfile.txt

Delete every letter f from the file


The tr command can do some nifty tricks when you specify ranges of characters to work on. Here’s an example of capitalizing lowercase letters to uppercase letters:

$ echo giovanni| tr a-z A-Z

Translate chris into GIOVANNI


The same result can be obtained with the following syntax:

$ echo giovanni| tr ‘[:lower:]’ ‘[:upper:]’

Translate chris into GIOVANNNI


About msotela

This blog is for anyone who wants to access the power of a Linux system as a systems administrator or user. You may be a Linux enthusiast, a Linux professional, or possibly a computer professional who is increasingly finding the Windows systems in your data center supplanted by Linux boxes.

Posted on March 16, 2009, in Unix/Linux. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: