Understanding Linux / UNIX tr command

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" 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"
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:]"

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 ' ' ' ' 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' 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

🐧 If you liked this page, please support my work on Patreon or with a donation.
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
33 comments… add one
  • vishal Mar 1, 2014 @ 4:40

    Write shell script that do equivalent to tr ‘is’ ‘are’ utility.

  • Sergei Sep 14, 2014 @ 13:21

    It’s a great article until:

    tr -d ‘nameserver’ ns.ipaddress.txt

    is given as an example of how to remove nameserver from /etc/resolv.conf. This should be removed from the article lest somebody does it in production somewhere.

  • bob Sep 30, 2014 @ 15:09

    Input Output
    a?$ ?tg
    Translation a?$ / ?tg / ttg
    How can I convert back with a second command in script? without using opposing script or aligning both translations.
    If in/out abcd/dcba translation works either way.
    I could switch in/out with a second script.
    Looking for something like
    tr a?$ ?tg
    maybe && or : with $input or echo tr ?tg a?$ in the same script.

    • bob Sep 30, 2014 @ 19:16

      Ex: input1output1 “print” output1output2 “print”
      I’m calling my script from terminal, but unable to pickup the printed output1 with tr2.
      I’m expecting to find a double output.
      Ex:hello/12334/hello or 12334/hello/12334

  • Wanderer Oct 26, 2014 @ 13:51

    Thank you :)

  • barsita ray May 12, 2015 @ 13:45

    write a shell program to find the initial of any name and display it using tr commnd.
    example:Rabindra NAth Tagore is given as input .
    Output will be R.N.Tagore.
    I cannot solve this and on friday(15.5.15) I have lab exam on this shell.

  • Diego Oct 22, 2016 @ 14:13

    Hi, can you explain me why this code doesn’t work ??

    $ echo hola que tal 12344 >> file
    $ tr "[:alpha:]" "[:upper:]" < file

    I want to replace all lower case in the file into upper case.

    Thanks

    • 🐧 Vivek Gite Oct 22, 2016 @ 14:56

      $ tr "[:lower:]" "[:upper:]"

      • Diego Oct 22, 2016 @ 15:46

        Thanks, i already now that , is just that can’t explain why my code it’s wrong

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.