Pages

Saturday, December 12, 2015

tr command one liners

Home

tr is an UNIX utility for translating, or deleting, or squeezing repeated characters. It will read from STDIN and write to STDOUT. tr stands for translate.

The syntax of tr command is:

$ tr [OPTION] SET1 [SET2]
Translation

If both the SET1 and SET2 are specified and ‘-d’ OPTION is not specified, then tr command will replace each characters in SET1 with each character in same position in SET2.

1.       Convert lower case to upper case

# echo the | tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
# echo the | tr [:lower:] [:upper:]
# echo the | tr a-z A-Z

2.       Translate braces into parenthesis

# tr '{}' '()' < inputfile > outputfile

3.       Translate white-space to tabs

# echo "This is for testing" | tr [:space:] '\t'

4.       Squeeze repetition of characters using -s

# echo "This   is   for testing" | tr [:space:] '\t'
# echo "This   is   for testing" | tr -s [:space:] '\t'
# echo "This  is  for testing" | tr -s [:space:] ' '

5.       Delete specified characters using -d option

# echo "the test string" | tr -d 't'

6.       To remove all the digits from the string, use

# echo "my username is samual007" | tr -d [:digit:]

7.       To remove all characters except digits, you can use the following.

# echo "my username is samual007" | tr -cd [:digit:]

8.       Remove all non-printable character from a file

# tr -cd [:print:] < file.txt

9.       Join all the lines in a file into a single line

# tr -s '\n' ' ' < file.txt


No comments:

Post a Comment