The unsung hero of text manipulation. Small, fast, and does one thing brilliantly: character-level kung fu.
Basic character replacement#
1
2
3
4
5
6
7
8
9
10
11
| # Convert lowercase to uppercase
echo "hello world" | tr 'a-z' 'A-Z'
# Output: HELLO WORLD
# Convert uppercase to lowercase
echo "HELLO WORLD" | tr 'A-Z' 'a-z'
# Output: hello world
# Replace spaces with underscores
echo "hello world" | tr ' ' '_'
# Output: hello_world
|
Delete characters#
1
2
3
4
5
6
7
8
9
10
| # Delete specific characters
echo "hello123world" | tr -d '0-9'
# Output: helloworld
# Delete spaces
echo "h e l l o" | tr -d ' '
# Output: hello
# Delete newlines
cat file.txt | tr -d '\n'
|
Squeeze repeated characters#
1
2
3
4
5
6
7
8
9
| # Squeeze multiple spaces to single space
echo "hello world" | tr -s ' '
# Output: hello world
# Squeeze repeated newlines
cat file.txt | tr -s '\n'
# Remove blank lines
cat file.txt | tr -s '\n' | grep .
|
Common use cases#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| # Convert Windows line endings to Unix
tr -d '\r' < windows.txt > unix.txt
# Remove all non-alphanumeric characters
echo "hello@world!123" | tr -cd '[:alnum:]'
# Output: helloworld123
# Replace multiple characters at once
echo "hello-world_test" | tr '_-' ' '
# Output: hello world test
# Convert CSV to TSV
cat file.csv | tr ',' '\t' > file.tsv
# ROT13 encoding
echo "hello" | tr 'A-Za-z' 'N-ZA-Mn-za-m'
|
Character classes#
1
2
3
4
5
| # Using POSIX character classes
tr '[:lower:]' '[:upper:]' # Lowercase to uppercase
tr -d '[:digit:]' # Delete all digits
tr -d '[:punct:]' # Delete punctuation
tr -d '[:space:]' # Delete all whitespace
|
Notes#
tr works on streams (stdin), not files directly- Cannot do regex patterns (use
sed for that) - Great for simple character-level transformations
- Very fast for large files