The tr Command in Linux Bash
-
Translate Strings With the
tr
Command in Linux Bash -
Use the
-d
Flag to Delete Characters in Linux Bash -
Use the
-s
Flag to Squeeze Characters in Linux Bash -
Use the
-c
Flag to Exclude Set in Linux Bash -
Get Input From the
cat
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:]'
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 '-' ' '
Yahya Irmak has experience in full stack technologies such as Java, Spring Boot, JavaScript, CSS, HTML.
LinkedInRelated Article - Linux Command
- The ps aux Command in Linux
- Differences Between Curl and Wget
- How to Export Command in Linux
- How to Use Linux Commands pushd and popd
- The top Command in Linux