Linux tr Command

Translate or Delete Characters - 10 Practical Examples with Detailed Explanations

Example 1

Convert Lowercase to Uppercase

$ echo "hello world" | tr 'a-z' 'A-Z'
HELLO WORLD
Translates all lowercase letters to uppercase using character ranges. The first set 'a-z' defines source characters, and the second set 'A-Z' defines replacement characters. Each character in the first set is mapped to the corresponding character in the second set. One of the most common uses of tr.
Alternative: tr '[:lower:]' '[:upper:]' works for all locales
Example 2

Convert Uppercase to Lowercase

$ echo "HELLO WORLD" | tr 'A-Z' 'a-z'
hello world
Translates all uppercase letters to lowercase. The reverse of Example 1. Useful for normalizing text input, creating case-insensitive comparisons, or standardizing filenames. Works character by character from stdin to stdout.
Character Classes: Use [:upper:] and [:lower:] for better portability across locales
Example 3

Delete Specific Characters

$ echo "Hello, World!" | tr -d ',!'
Hello World
Deletes specified characters using the '-d' option. All occurrences of comma and exclamation mark are removed from the input. No replacement set is needed when deleting. Essential for cleaning data, removing punctuation, or stripping unwanted characters.
Use Case: Remove special characters from user input or sanitize data
Example 4

Delete All Digits

$ echo "Order 123 costs $45.67" | tr -d '0-9'
Order costs $.
Removes all numeric digits from the input using a character range. The range '0-9' matches all digits from 0 to 9. Useful for extracting non-numeric content or removing version numbers, IDs, or other numeric data from text.
Alternative: tr -d '[:digit:]' for better readability
Example 5

Squeeze Repeated Characters

$ echo "Hello World" | tr -s ' '
Hello World
Squeezes multiple consecutive occurrences into a single occurrence using the '-s' option. This example replaces multiple spaces with single spaces. Extremely useful for normalizing whitespace, cleaning log files, or formatting output. Works with any character or character set.
Common Use: Clean up whitespace in text files or log parsing
Example 6

Replace Multiple Characters

$ echo "phone: 123-456-7890" | tr '-:' ' '
phone 123 456 7890
Replaces multiple different characters with a single character. Both hyphens and colons are replaced with spaces. When the second set has fewer characters than the first, the last character in the second set is repeated for all remaining characters in the first set.
Character Mapping: First set defines what to replace, second set defines replacements
Example 7

Remove Non-Printable Characters

$ cat file_with_control_chars.txt | tr -cd '[:print:]\n'
# Keeps only printable characters and newlines # Removes control characters, NULL bytes, etc.
Removes all non-printable characters using '-c' (complement) and '-d' (delete). The complement inverts the set, so '[:print:]' becomes "everything except printable characters". Adds \n to preserve newlines. Perfect for cleaning binary corruption or control characters from text files.
File Cleaning: Essential for fixing corrupted text files or binary-contaminated logs
Example 8

Convert Spaces to Newlines

$ echo "one two three four" | tr ' ' '\n'
one two three four
Converts spaces to newlines, putting each word on its own line. Useful for converting space-delimited data to line-delimited format for further processing with tools like grep, sort, or awk. Common in text processing pipelines.
Pipeline Use: Prepare data for line-based text processing tools
Example 9

ROT13 Encryption

$ echo "Hello World" | tr 'A-Za-z' 'N-ZA-Mn-za-m'
Uryyb Jbeyq
Implements ROT13 cipher (rotate by 13 positions) for simple text obfuscation. Each letter is replaced by the letter 13 positions after it in the alphabet. Applying ROT13 twice returns the original text. While not secure encryption, it's useful for spoiler protection or simple obfuscation.
Reversible: Apply the same command again to decode: echo "Uryyb Jbeyq" | tr 'A-Za-z' 'N-ZA-Mn-za-m'
Example 10

Remove All Whitespace

$ echo "Hello World From Unix" | tr -d '[:space:]'
HelloWorldFromUnix
Removes all whitespace characters including spaces, tabs, and newlines using the [:space:] character class. Results in continuous text with no spacing. Useful for compacting data, creating identifiers, or preparing text for specific parsing requirements.
Data Cleaning: Useful for creating compact keys or removing formatting
Bonus 1

Convert Windows Line Endings to Unix

$ tr -d '\r' < windows_file.txt > unix_file.txt
# Removes carriage return characters # Converts CRLF (Windows) to LF (Unix) line endings
Removes carriage return characters (\r) to convert Windows-style line endings (CRLF) to Unix-style (LF). Essential when transferring text files between Windows and Unix systems. Prevents issues with scripts and tools that expect Unix line endings.
Cross-Platform: Fix line ending issues from Windows files on Unix systems
Bonus 2

Create URL-Safe Strings

$ echo "My File Name (2025).txt" | tr -cs '[:alnum:]' '-' | tr '[:upper:]' '[:lower:]'
my-file-name-2025-txt
Creates URL-safe or filename-safe strings by: 1) using '-c' to complement [:alnum:] (keeping only letters and numbers), 2) '-s' to squeeze multiple non-alphanumeric characters into single hyphens, 3) converting to lowercase. Perfect for creating slugs, safe filenames, or URL paths.
Web Development: Essential for generating SEO-friendly URLs and safe filenames
Reference

Common tr Options and Character Classes

Basic Syntax: tr [OPTION] SET1 [SET2] Options: -c, -C Complement SET1 (use all characters NOT in SET1) -d Delete characters in SET1 -s Squeeze repeated characters in SET1 -t Truncate SET1 to length of SET2 Character Ranges: a-z All lowercase letters A-Z All uppercase letters 0-9 All digits Character Classes (POSIX): [:alnum:] Alphanumeric characters [:alpha:] Alphabetic characters [:blank:] Space and tab [:digit:] Digits 0-9 [:lower:] Lowercase letters [:upper:] Uppercase letters [:space:] Whitespace (space, tab, newline, etc.) [:punct:] Punctuation characters [:print:] Printable characters [:cntrl:] Control characters Special Characters: \n Newline \t Tab \r Carriage return \\ Backslash \NNN Octal value NNN Common Examples: tr 'a-z' 'A-Z' Lowercase to uppercase tr -d '\r' Remove carriage returns tr -s ' ' Squeeze multiple spaces tr -d '[:punct:]' Remove punctuation tr ' ' '\n' Spaces to newlines tr -cd '[:print:]' Keep only printable chars tr -cs '[:alnum:]' '[\n*]' Keep alphanumeric, squeeze others to newline Practical Patterns: # Clean data tr -cd '[:print:]\n' ⁢ dirty.txt > clean.txt # Create slug echo "$title" | tr '[:upper:]' '[:lower:]' | tr -cs '[:alnum:]' '-' # Count words (space to newline) tr -cs '[:alnum:]' '\n' < file.txt | sort | uniq -c # Remove numbers tr -d '[:digit:]' < input.txt # Convert to uppercase tr '[:lower:]' '[:upper:]' < file.txt # Fix line endings tr -d '\r' <` windows.txt > unix.txt
Comprehensive reference for tr command including options, character classes, special characters, and common usage patterns for text transformation and data cleaning tasks.