In this article, we will see information more about 10 useful tr commands in Linux.
tr (short for translate) is a useful command line utility that translate, squeeze, and/or delete characters from standard input, writing to standard output. It is a useful program for manipulating text on the command line.
The syntax of the tr command:
# tr [OPTION]… SET1 [SET2]
1 Convert all text in from lower case to upper case and vise versa
# cat file.txt | tr [:lower:] [:upper:]
It convert text from lower case to upper case.
2. The alternative command for above command is as shown below
# cat linux.txt | tr [a-z] [A-Z]
3. Input and output redirection
# tr [a-z] [A-Z] < file1.txt > file2.txt
Using this command you can send input to tr using the input redirection and redirect the output to a file using the same command.
4. Remove characters from file
# cat file.txt | tr -d ‘ ‘
Above command will remove white space from the file. You can mention any character that you want to remove.
5. Remove double characters
# cat domains.txt | tr -s ‘ ‘
Above command will remove double white spaces. You can use the -s option to squeeze the characters leaving only one occurrence of it.
6. Display number from the file
# cat file.txt | tr -cd “[:digit:]\n”
If you want to display number and remove all letters, above command will help you. The -c option tells tr to use the complement in the given of SET.
7. Break line in to single word
# cat file.txt | tr ” ” “\n”
This command will break the single line of words into multiple lines.
8. Join multiple lines in one single sentence
# tr “\n” ” ” < file.txt
9. It is also possible to translate just a single character, for instance a space into a “ : ” character, as follows.
# echo “hostnextra.com =>Linux-HowTos,Guides,Tutorials” | tr ” ” “:”
10. Man page
# man tr
To learn more about tr run above command.
In this article, we have seen 10 useful tr commands in Linux.