tr stands for translate, which finds and replaces characters. It is good for manipulating text on the CLI. It has 2 mandatory sets, where SET1
translates into SET2
characters.
There are certain special character maps to special values.
-
\a
alert character -
\b
backspace -
\f
form-feed -
\n
newline -
\r
carriage return -
\t
tab -
\v
vertical tab
You have 2 options to run the tr
command. In this article, I will be using option 1 most of the time but you are free to choose other options as well.
1
2
3
4
5
# option 1
echo "Yafiz Abraham" | tr 'SET1' 'SET2'
# option 2
cat filename.txt | tr 'SET1' 'SET2'
To convert lower case letters into upper case letters.
1
2
echo "hello world" | tr 'a-z' 'A-Z'
echo "hello world" | tr '[:lower:]' '[:upper:]'
To convert all upper case letters into lower case letters.
1
2
echo "HELLO WORLD" | tr 'A-Z' 'a-z'
echo "HELLO WORLD" | tr '[:upper:]' '[:lower:]'
To remove spaces or any other characters, use -d
flag which means delete.
1
2
echo "hello world" | tr -d ' '
echo "hello world" | tr -d 'ld'
To find and replace any characters, use -s
flag which means squeeze. Run the following command to remove all spaces and keep only a single space instead.
1
2
echo "hello world" | tr -s ' '
echo "hello world" | tr -s '[:space:]'
You can also find spaces and replace them with a single hyphen.
1
echo "hello world" | tr -s ' ' '-'
You can also find a single space and replace it with multiple spaces or a single tab (2 or more spaces).
1
echo "I want you to add more space" | tr -s ' ' '\t'
You can also find and replace a single character.
1
echo "hello world" | tr -s "o" "H"
To find numbers and replace them with x characters.
1
2
echo "HELLO 778df99 world 123aaa456" | tr '0-9' 'x'
echo "HELLO 778df99 world 123aaa456" | tr '[:digit:]' 'x'
Run the following command to find out numbers only from the given string.
-
\n
is adding a new line at the end of each statement. -
-c
flag which means complement, so this flag makes sure that-d
flag should remove everything except the given string (except numbers0-9
).
1
2
echo "HELLO 778df99 world 123aaa456" | tr -cd '0-9\n'
echo "HELLO 778df99 world 123456" | tr -cd '[:digit:]\n'
To find out alphabets only from the given string either small letters and big letters.
1
2
echo "HELLO 7789df9 world 123dfaa456" | tr -cd 'a-zA-Z\n'
echo "HELLO 778df99 world 123asdf456" | tr -cd '[:alpha:]\n'
To find out letters and digits only from the given string and remove whatever is left.
1
2
echo "HELLO 77899 #$%as^#$ world 123456 +;.sdasdfasffQ@{as" | tr -cd 'a-zA-Z0-9\n'
echo "HELLO 77899 #$%^asdjw234#$ world 123456 +;.123Q@{" | tr -cd '[:alnum:]\n'