Linux tr Command with Examples

May 10, 2022

Introduction

The tr command is a Linux command-line utility that translates or deletes characters from standard input (stdin) and writes the result to standard output (stdout). Use tr to perform different text transformations, including case conversion, squeezing or deleting characters, and basic text replacement.

Since tr can't read a file directly and outputs the results in standard output, it is often used with pipes (|) and redirects (>>) to allow more complex file content processing.

In this tutorial, you will learn to use the Linux tr command.

Linux tr command tutorial with examples.

Prerequisites

  • A system running Linux.
  • Access to the terminal (Ctrl + Alt + T).

Linux tr Command Syntax

The basic tr command syntax is:

tr [options] SET1 [SET2]

Options

Running tr without any options replaces each of the characters specified in SET1 with the characters from SET2 that have the same position.

For example:

Running the tr command without options.

In the example above, the echo command's output is piped into the tr command, replacing each instance of e with o.

SET

SETs are strings of characters. The command accepts the following interpreted sequences for character matching:

SequenceInterpretation
\NNNCharacters with the NNN octal value (1 to 3 octal digits).
\\Backslash.
\aAn audible bell character.
\bBackspace.
\fForm feed.
\nNewline character.
\rReturn character.
\tHorizontal tab.
\vVertical tab.
CHAR1-CHAR2All characters from CHAR1 to CHAR2 in an ascending order.
[CHAR*]Copies CHAR* in SET2 up to the length of SET1.
[CHAR*REPEAT]Repeats copies of CHAR. Repeats octal if starting with 0.
[:alnum:]All letters and digits.
[:alpha:]All letters.
[:blank:]Horizontal whitespaces.
[:cntrl:]All control characters.
[:digit:]All digits.
[:graph:]Printable characters, excluding space.
[:lower:]All lowercase characters.
[:print:]Printable characters, including space.
[:punct:]All punctuation characters.
[:space:]Horizontal or vertical whitespace characters.
[:upper:]All uppercase letters.
[:xdigit:]Hexadecimal digits.
[=CHAR=]All characters equivalent to CHAR.

Note: Another great Unix text stream editor is SED. The tool allows you to search, replace, add, and delete lines in a text file without opening it in a text editor.

Linux tr Command Options

The options provide additional character transformation actions. The available options are:

OptionDescription
-CComplements the characters in SET1, including every character in the output except the ones specified.
-cComplements the values in SET1. Operations apply to characters that are not in the given set.
-dDeletes characters from the SET1 input.
-sSqueezes repeated characters specified in the last operand (either SET1 or SET2) and replaces them with a single occurrence of that character.
-tTruncates SET1 to the length of SET2.
-uEnsures that any output is unbuffered.
--helpDisplays the help file with all available options.
--versionDisplays the program version information.

Linux tr Examples

Below are examples of using the tr command with different options to transform input text.

Change Character Case

There are three ways of changing character case with tr:

1. Specify the Exact Characters You Want Converted

Specify which characters from the input you want to convert. This option changes the character case or entire characters, replacing the ones from SET1 with the ones from SET2.

For example:

Character case conversion using tr.

2. Specify Character Range for Conversion

Specifying a range allows tr to change the case of any character within that specified range. The following example shows how to convert uppercase characters to lowercase:

Converting character case using ranges.

Press CTRL+C to exit input mode.

3. Specify Interpreted Sequences

Match and convert characters by specifying interpreted sequences. For example, the sequence for lowercase characters is [:lower:], and the sequence for uppercase characters is [:upper:]. Specifying the two sequences instructs tr to match and convert the character case:

Converting character case using sequences.

The example above shows how tr converts uppercase characters to lowercase.

Remove Repeated Characters

The -s option squeezes repeated characters into a single instance of that character. The option is particularly useful when converting whitespaces to tabs or newline characters, and the input text contains multiple continuous whitespace characters.

For example, the following input contains multiple whitespace characters. Converting them to tabs without squeezing provides the following result:

Converting whitespace characters into tabs using the tr command.

To avoid multiple tabs and whitespaces in the output, specify the -s option:

Squeezing multiple instances of a character into a single one.

Delete Characters

Remove specific characters using the -d option. In the following example, tr deletes each instance of the e character:

Using tr to delete specific characters.

Optionally, specify a group of characters using interpreted sequences. For example, remove all digits by specifying the [:digit:] sequence:

Removing a group of characters from a set.

Complement Sets

Use the -c option to complement the characters in SET1. In the following example, we remove all characters except digits:

Complementing a set using tr.

All characters not in the specified set (in this case, everything except digits) are removed.

Remove Newline Characters

Shrink the space a text occupies by converting newline characters into spaces. The content then appears in a single line.

In the following example, we use the cat command to open a text file and pipe it into tr to remove newline characters:

Removing the newline character from a file with tr.

Redirect Into tr

An alternative to piping is to use redirection to feed content into tr. Additionally, you can use redirection to save the tr output in a file.

The following example shows how to remove all non-printable characters from a file whose contents are redirected into tr:

Redirecting a file's contents into tr.

Truncate Set

By default, if SET1 is longer than SET2, tr reuses the last character from SET2 when processing the input. For example:

Replacing characters using the tr command.

Since SET1 is longer than SET2, tr reuses the last character from SET2, in this case, 2.

Use the -t option to truncate SET1 to the length of SET2:

Truncating the set length in tr.

The -t option instructs tr to truncate SET1 to the length of SET2 and replaces only the first two characters.

Remove Diacritics

Use the [=CHAR=] sequence to match all characters equivalent to the specified one. For example, the sequence can identify and remove diacritics from characters.

Remove diacritics from characters using tr.

Print Each Word Separately

Print a file's contents line by line using the -c option and replace the non-alphanumerical characters with a newline character.

Printing each word from a file separately.

Note: If you prefer using Bash, see how to read a file line by line.

The output is now displayed one word at a time.

Save Output to File

Since tr doesn't change a file's contents directly, it also doesn't save any changes you make. Save the output to a file by redirecting it as shown in the following example:

Redirecting the tr command output to a file.

Opening the new file with cat shows that the changes have been saved.

Conclusion

This tutorial showed how to use the tr command and its available options for various text transformations. Check out other Linux text utilities in our guides for the sort command and less terminal pager, or see the best Linux text editors.

Was this article helpful?
YesNo
Bosko Marijan
Having worked as an educator and content writer, combined with his lifelong passion for all things high-tech, Bosko strives to simplify intricate concepts and make them user-friendly. That has led him to technical writing at PhoenixNAP, where he continues his mission of spreading knowledge.
Next you should read
wc Linux Command with Examples
April 5, 2022

The wc command is part of the coreutils Linux package containing the GNU core utilities. This tutorial will show you how to use the wc command and its options.
Read more
How to Use the Linux history Command
March 3, 2022

The Linux bash shell saves a command history list, allowing you to review and reuse previous commands. Learn how to manage this list using the Linux history command.
Read more
How to Use the locate Command in Linux
January 25, 2022

The locate command is a utility that allows users to quickly search for files or directories in Linux. This tutorial shows how to install and effectively use the locate command.
Read more
How to Use the Linux head Command
January 5, 2022

The head commands lists the first ten lines of a file in standard output. Follow this guide and learn how to use the head command and its options (with examples).
Read more
  • © 2022 Copyright phoenixNAP | Global IT Services. All Rights Reserved.