Text Transformation Techniques
Character Translation
Basic Character Replacement
echo "hello" | tr 'h' 'H' ## Replaces 'h' with 'H'
Multiple Character Translation
echo "welcome" | tr 'wel' 'WEL' ## Translates multiple characters
Lowercase to Uppercase
echo "labex tutorial" | tr '[:lower:]' '[:upper:]'
Uppercase to Lowercase
echo "LABEX TUTORIAL" | tr '[:upper:]' '[:lower:]'
Character Deletion Techniques
Deleting Specific Characters
echo "hello world" | tr -d 'l' ## Removes all 'l' characters
Deleting Multiple Characters
echo "123-456-7890" | tr -d '[-]' ## Removes hyphens
Character Squeezing
Removing Repeated Characters
echo "hello world" | tr -s ' ' ## Squeezes multiple spaces
Squeezing Specific Characters
echo "mississippi" | tr -s 'i' ## Reduces repeated 'i'
echo "abc123" | tr 'a-z' 'A-Z' ## Converts lowercase to uppercase
echo "hello123" | tr -c '[:alpha:]' '*' ## Replace non-alphabetic chars
Option |
Description |
Example |
-d |
Delete characters |
tr -d '0-9' |
-s |
Squeeze repeated characters |
tr -s ' ' |
-c |
Complement set |
tr -c '[:print:]' '\n' |
graph TD
A[Input Text] --> B{tr Transformation}
B --> |Character Translation| C[Translated Text]
B --> |Character Deletion| D[Filtered Text]
B --> |Character Squeezing| E[Compressed Text]
Common Use Cases
- Text normalization
- Data cleaning
- Simple text encryption
- Formatting conversion
By mastering these techniques, users can perform complex text transformations efficiently using the tr
command in LabEx Linux environments.