Understanding Linux / UNIX tr command

Understanding Linux / UNIX tr command

The tr command (short for "translate") is a utility in Linux and Unix-like operating systems that is used to translate or delete characters from standard input. It is commonly used to remove unwanted characters from a string or to translate one set of characters into another.

Here is the basic syntax for using the tr command:

refer t‮:o‬lautturi.com
tr [OPTIONS] SET1 SET2

SET1 is the set of characters that you want to translate or delete, and SET2 is the set of characters that you want to translate SET1 into (for translation) or to use as a placeholder (for deletion).

Here are some examples of using the tr command:

  • To translate all lowercase letters to uppercase:
echo "hello world" | tr a-z A-Z
  • To delete all vowels from a string:
echo "hello world" | tr -d aeiou
  • To translate all spaces to underscores:
echo "hello world" | tr ' ' '_'
  • To delete all non-printable characters:
tr -dc '\011\012\015\040-\176' < file.txt

The tr command has several options that can be used to modify its behavior. For example, the -c option inverts the sets, so that SET1 specifies the characters that should be kept, and SET2 is ignored. The -s option reduces repeated characters in the output to a single occurrence.

Created Time:2017-10-30 14:27:29  Author:lautturi