The tr Command in Linux Bash

Yahya Irmak Jan 30, 2023
  1. Translate Strings With the tr Command in Linux Bash
  2. Use the -d Flag to Delete Characters in Linux Bash
  3. Use the -s Flag to Squeeze Characters in Linux Bash
  4. Use the -c Flag to Exclude Set in Linux Bash
  5. Get Input From the cat Command in Linux Bash
The tr Command in Linux Bash

In Linux, we can do string manipulations such as concatenation, truncation, and finding words in the text with Bash scripting.

This article will explain how to translate or delete characters with the tr command in Linux Bash.

Translate Strings With the tr Command in Linux Bash

The tr command means to translate. It is used to delete, translate and squeeze characters.

It takes standard input, processes it, and writes it to standard output.

Syntax:

tr '[SET1]' '[SET2]'

Here, the SET1 represents the letters to be found in the text, and the SET2 represents the letters to be replaced.

For example, we can use one of the commands below to convert all lowercase letters to uppercase.

echo "lowercase string" | tr '[:lower:]' '[:upper:]'
echo "lowercase string" | tr '[a-z]' '[A-Z]'

To do the opposite of this:

echo "UPPERCASE STRING" | tr '[A-Z]' '[a-z]'
echo "UPPERCASE STRING" | tr '[:upper:]' '[:lower:]'

uppercase lowercase convert

For the use of find and replace:

echo "test string with dash" | tr ' ' '-'

With this command, all space characters in the text given as input will be found and replaced with a dash.

test-string-with-dash

Use the -d Flag to Delete Characters in Linux Bash

The -d flag is used to delete characters, not translate them. It takes a single character set and deletes those characters from the text.

`echo "hxexlxlxo" | tr -d 'x'`

Output:

hello

Use the -s Flag to Squeeze Characters in Linux Bash

The -s flag translates consecutive characters in the text with a single occurrence of that character.

echo "tttessttt sstriinngg" | tr -s 'a-z'

Output:

test string

Use the -c Flag to Exclude Set in Linux Bash

The -c flag translates all characters except those specified in SET1 to characters in SET2.

`echo "a1@b2'c3&d" | tr -c '[a-z]' ' '`

Output:

a  b  c  d

Get Input From the cat Command in Linux Bash

You can change the contents of a file using the tr command. We can read the file with the cat command and pipe its contents to the tr command.

cat file.txt | tr '-' ' '

tr with cat command

Author: Yahya Irmak
Yahya Irmak avatar Yahya Irmak avatar

Yahya Irmak has experience in full stack technologies such as Java, Spring Boot, JavaScript, CSS, HTML.

LinkedIn

Related Article - Linux Command

Related Article - Bash Command