tr - macOS


Overview

tr is a versatile text processing tool for character-based transformations. It allows users to substitute, delete, or translate characters within a given text. Primarily used in scripting environments or for quick text manipulation tasks, tr offers flexibility in character manipulation.

Syntax

tr [OPTIONS] [SET1] [SET2]

Options/Flags

  • -cd: Delete all characters in SET1 that are not in SET2.
  • -d: Delete all characters in SET1.
  • -s: Squeeze multiple occurrences of a character in SET1 into a single occurrence.
  • -t: Translate characters in SET1 to their corresponding characters in SET2.

Examples

Substitute Characters:

echo "Hello World" | tr 'a-z' 'A-Z'

Output:

HELLO WORLD

Delete Characters:

echo "programming" | tr -d 'aeiou'

Output:

prgrmming

Translate Characters:

echo "Lorem ipsum" | tr 'aeiou' '12345'

Output:

L1r1m 1ps2m

Common Issues

  • Empty Input: Ensure that the input text is not empty before using tr.
  • Invalid Character Sets: Check that SET1 and SET2 contain valid characters.
  • Matching Characters: If the two character sets contain any matching characters, the translation may not occur as expected.

Integration

tr can be combined with other commands to enhance its functionality:

echo "my_file.txt" | tr '[a-z]' '[A-Z]' > "MY_FILE.TXT"
  • sed: Stream editor for more complex text manipulation.
  • awk: Advanced text processing language.
  • grep: Search for patterns in text.