0
0
Bash Scriptingscripting~5 mins

tr for character transformation in Bash Scripting

Choose your learning style9 modes available
Introduction
The tr command changes or deletes characters in text. It helps fix or clean text quickly.
You want to change all lowercase letters to uppercase in a file.
You need to remove all digits from a text stream.
You want to replace spaces with underscores in a filename.
You want to delete all punctuation marks from a sentence.
You want to squeeze repeated characters into one (like multiple spaces into one).
Syntax
Bash Scripting
tr [options] SET1 [SET2]
SET1 is the set of characters to replace or delete.
If SET2 is given, characters in SET1 are replaced by corresponding characters in SET2.
Examples
Converts all lowercase letters to uppercase.
Bash Scripting
echo "hello" | tr 'a-z' 'A-Z'
Deletes all digits from the input.
Bash Scripting
echo "123abc" | tr -d '0-9'
Replaces spaces with underscores.
Bash Scripting
echo "hello  world" | tr ' ' '_'
Sample Program
This script takes a string, changes all lowercase letters to uppercase using tr, and prints the result.
Bash Scripting
#!/bin/bash

# Convert lowercase to uppercase
input="hello world"
output=$(echo "$input" | tr 'a-z' 'A-Z')
echo "$output"
OutputSuccess
Important Notes
tr works on standard input and outputs to standard output, so use pipes or redirection.
The -d option deletes characters from the input.
The -s option squeezes repeated characters into one.
Summary
tr changes or deletes characters in text streams.
Use it to convert cases, delete unwanted characters, or replace characters.
It reads from input and writes transformed text to output.