Enhancing Skills

awk: Pattern scanning and processing language

The tr command is used to translate or delete characters from input data. It’s commonly used for tasks such as changing character case, replacing specific characters, or deleting unwanted characters.

Basic Syntax

tr [options] SET1 [SET2]

Options

  • -d : Delete characters specified in SET1.
  • -s : Squeeze multiple adjacent occurrences of characters in SET1 into a single occurrence.
  • -c : Complement the set of characters in SET1.

Examples


1. Convert Lowercase to Uppercase

Command:

echo "hello world" | tr 'a-z' 'A-Z'

Sample Input:

hello world

Sample Output:

HELLO WORLD

Explanation:

  • 'a-z' specifies the range of characters to convert from lowercase.
  • 'A-Z' specifies the range of characters to convert to uppercase.

2. Delete Specific Characters

Command:

echo "hello 123" | tr -d '0-9'

Sample Input:

hello 123

Sample Output:

hello 

Explanation:

  • -d '0-9' deletes all digits from the input.

3. Squeeze Multiple Spaces into a Single Space

Command:

echo "hello    world" | tr -s ' '

Sample Input:

hello    world

Sample Output:

hello world

Explanation:

  • -s ' ' squeezes multiple spaces into a single space.

4. Complement Character Set

Command:

echo "hello world" | tr -c 'a-z ' 'X'

Sample Input:

hello world

Sample Output:

XXXXX XXXXX

Explanation:

  • -c 'a-z ' complements the set of characters specified, replacing everything not in the set with X.

Summary

The tr command is a versatile tool for transforming or deleting characters from text input. It’s useful for tasks like case conversion, character replacement, and formatting text by removing unwanted characters or squeezing repetitions.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.