Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Tr Command in Linux?
3.
Syntax of Linux tr Command
4.
tr Options
5.
Examples of tr Command
5.1.
Changing the Character Case
5.2.
Removing the Repeated Characters
5.3.
Deleting Characters
5.4.
Complement Set
5.5.
Removing Digits From a String
5.6.
Remove Newline Characters
5.7.
Redirect Into tr
5.8.
Truncate Set
5.9.
Remove Diacritics
5.10.
Print Each Word Separately
5.11.
Save Output to File
6.
How to convert lower case characters to upper case.
7.
How to delete specified characters using -d option.
8.
How to translate white-space characters to tabs.
9.
How to translate braces into parenthesis.
10.
How to squeeze a sequence of repetitive characters using -s option
11.
Frequently Asked Questions
11.1.
What is the tr command in bash?
11.2.
What does tr ‘\n’ do?
11.3.
What is tr in script?
12.
Conclusion
Last Updated: Mar 27, 2024
Easy

tr Command In Linux

Author Sajid Khan
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

This article explains the use of the tr command in Linux, the syntax used for the tr command in Linux. We will see, in detail, how it is used with some examples. We will also look into the different variants of the tr command.

tr command in linux

What is Tr Command in Linux?

This command is a command-line utility in UNIX that is used for translating or deleting characters from standard input (stdin) and writing the result into the standard output (stdout).

It allows a lot of transformations like uppercase to lowercase, squeezing the repeating characters, deleting characters, and find and replace features.

The tr (translate) command is usually used with pipe (|) and redirect (>>) symbols for that allow content processing of files.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax of Linux tr Command

The Syntax for the basic tr command is:

$ tr [options] SET1 [SET2]

The tr command takes two arguments, SET1 and SET2SET1 is used for the input characters, and SET2 are the characters to which SET1 characters will be translated to. When some flags are used with the tr command, SET2 might get used optionally.

tr Options

If we use the tr command without any option then the characters in SET1 will be replaced with characters from SET2 belonging to the same position.

Some of the available options are given below.

  • -C: This option complements every character in SET1 except those specified.
     
  • -c: This option complements the values in SET1. It applies to only those characters that aren’t specified in the given set.
     
  • -d: This option deletes the from the SET1 in the output.
     
  • -s: This option is used to replace the multiple occurrences of the character in SET1 with one occurrence.
     
  • -t: This option is used to truncate the length of SET1 to the length of SET2.

Examples of tr Command

Changing the Character Case

To do this, we can. 

  • Specify the characters whose cases we want to be converted

$ tr HLL hll
HELLO
hEllO

 

  • We can provide the range for conversion.

$ tr A-Z a-z
CODING NINJAS
coding ninjas

 

  • We can use predefined character classes.
$ tr [:upper:] [:lower:]
CODESTUDIO
Coding Ninjas Studio

Removing the Repeated Characters

By using the -s option, we can squeeze multiple instances of a character into one single occurrence; this can be useful in removing whitespaces to tabs or newline.

As shown in the example below.

$ echo this    is    coding    Ninjas | tr -s “ ”
this is coding Ninjas

Deleting Characters

We can remove the specific character using the -d option. In the example, ‘l’ is removed from the input string.

$ tr -d ‘l’
hello 
heo

Complement Set

We can use the -c option to complement the characters in SET1. Here we remove all the characters except the digits from the given string.

$ echo “Aditya's roll no is 134” | tr -cd [:digit:]
134

Removing Digits From a String

We can use the -d option, as shown below, to remove the digits from a string.


$ echo “Aditya's roll no is 134” | tr -d [:digit:]
Aditya's roll no is

Remove Newline Characters

The following example shows how we can remove a newline characters:

$ cat test1.txt 
Line one 
Line two 
Line three 
Line four 
Line Five


Here, “-d” option is used to specify the “tr” command to remove a character. A general use for the “tr” command is to remove “new line” characters from a file. The new line character is specified as “\n”.

$ cat test1.txt | tr -d "\n"


Output

Line oneLine twoLine threeLine fourLine Five

Redirect Into tr

Instead of Piping, we have an alternative Redirection of feed content into tr. Also, we can use redirection to save the tr output in a file. Here , test.txt file has the content “ Hello Welcome to CodingNinjasThis is the tr command tutorial”.

Example

$ tr -cd [:print] < test.txt
HelloWelcome to CodingNinjasThis is the tr command tutorial.

Truncate Set

If SET1 is longer then SET2 by default, tr uses the last character from SET2 when processing the input. For example:

$ echo “codingninja” | tr coding 23


output

233333ninja

As, SET1 is longer than SET2, tr reuses the last character from SET2, in this case, 3. By using the “-t” option to truncate SET1 to the length SET2:

$ echo “codingninja” | tr -t coding 23


Output

23dingninja

Remove Diacritics

We can use the [=CHAR=] sequence to match all characters equal to the specified one. For example, the sequence can detect and remove diacritics from characters.

$ cat text.txt
Hello, let's meet at a cafe`!
$ cat test.txt | tr “[=e=]” “e”
Hello, let's meet at a cafe!

Print Each Word Separately

With the help of the “-c” option, we can print the file's content line by line and also replace the non-alphanumerical characters with a newline character.

$ echo “ Welcome to Coding Ninja Studio" | tr -cs [:alnum:] '\n'


Output

Welcome
to
Coding
Ninjas 
Studio

Save Output to File

tr does not change a file's content directly also it doesn't save any changes we make. So we can save the output to a file by redirecting it as shown below:

$ tr -cd [:print] < test.txt > newredirected.txt
$ cat newredirected.txt


Output

HelloWelcome to CodingNinjasThis is the tr command tutorial.

How to convert lower case characters to upper case.

To convert lower case characters to upper case, you can use the tr command with the character classes for lower case and upper case letters as follows:

echo "welcome to coding ninjas" | tr '[:lower:]' '[:upper:]'


tr '[:lower:]' '[:upper:]': This part of the command converts all the lower case characters in the input text to their corresponding upper case characters.

The command will then convert all the lower case letters to their upper case counterparts, resulting in the following output:

WELCOME TO CODING NINJAS

How to delete specified characters using -d option.

You can use echo to print the input text, and then use tr -d 'con' to delete the characters 'c', 'o', and 'n' from the input text. 

echo "hello ninjas welcome to coding ninjas" | tr -d 'con'


The output displays the modified text with the specified characters removed.

Output:

hell ijas welme t dig ijas

How to translate white-space characters to tabs.

To translate white space character to tabs you can use tr ' ' '\t'.

In this example, the tr command translates each space character ' ' to a tab character '\t'.

echo "This is    coders    paradise on      earth." | tr ' ' '\t'


Output:

This    is                              coders                          paradise        on                                     earth.

How to translate braces into parenthesis.

To translate braces into parentheses we simply use tr '{}' '()'.

In this example, the tr command translates each curly brace character {} to a corresponding parenthesis character ().

echo "This is a {coding} platform {codingninjas}." | tr '{}' '()'


Output:

This is a (coding) platform (codingninjas).

How to squeeze a sequence of repetitive characters using -s option

You can use the  tr command with the -s option. 

It squeezes multiple consecutive space characters into a single space character, effectively removing the extra spaces.

echo "This    is    coding    ninjas." | tr -s ' '


Output:

This is coding ninjas.

Frequently Asked Questions

What is the tr command in bash?

The tr command in bash is used for translating or deleting characters. It supports a range of transformations which includes squeezing repeating characters, uppercase to lowercase, deleting specific characters, and basic find and replace.

What does tr ‘\n’ do?

A common use of the “tr” command is to remove “new line” characters from a file. The new line character is specified as “\n”.

What is tr in script?

The tr command is a UNIX command-line utility to translate or delete characters. It supports a range of transformations which includes squeezing repeating characters, uppercase to lowercase, deleting specific characters, and basic find and replace.

Conclusion

In this article we saw what is the tr command in Linux, we looked into the syntax of the tr command and saw various examples showing how to change these arguments to achieve the desired result.

Recommended Reads: 

Features of linux operating system

Touch command in linux

Nmap commands

Also, check out some of the Guided PathsContests, and Interview Experiences to gain an edge only on Coding Ninjas Studio.

Previous article
Ubuntu Operating System
Next article
Tail Command in Linux
Live masterclass