tr Command in Linux: Translate, Delete, and Squeeze Characters
Learn tr command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
9 min read
Learn tr command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What tr Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
Understanding the tr command in linux provides command-line practitioners with one of Unix's fastest and most streamlined character transformation filters. Short for 'translate', tr is a pure stream processing utility designed specifically to map, squeeze, or delete individual bytes and characters as text flows through standard input and standard output.
The tr command in Linux translates, squeezes, or deletes characters from standard input, writing the transformed byte stream to standard output. Run tr 'a-z' 'A-Z' to convert text to uppercase, tr -d '\r' to strip Windows carriage returns from files, or tr -s ' ' to squeeze multiple consecutive spaces into a single space.
Unlike more complex text utilities such as sed or awk, tr does not accept file paths as command-line arguments. Instead, it adheres strictly to the Unix pipeline philosophy: it reads byte streams directly from standard input (file descriptor 0) and emits results to standard output (file descriptor 1). This specialized design allows tr to execute with zero parsing overhead and maximum throughput.
From converting letter casing and standardizing delimiter formats to sanitizing user input and stripping carriage return characters (CRLF) from cross-platform configuration files, tr is an indispensable building block in robust shell scripts and data processing pipelines.
What tr Does and When to Use It
At the architectural level, GNU coreutils tr relies on a direct 256-byte lookup table (or wide-character translation map) allocated in memory upon invocation. When translating characters from SET1 to SET2, tr populates an array where each byte value (0 to 255) maps directly to its corresponding replacement byte. When scanning incoming data via raw read(2) syscalls, tr executes a simple tight loop that indexes incoming bytes into this lookup array, requiring no branching or complex evaluation logic.
When deleting characters (-d), tr marks matched bytes in a bitmask; bytes with a set bit are skipped and omitted from the write(2) buffer. When squeezing repeated characters (-s), tr maintains a single-byte state register tracking the previously emitted byte; if the current byte matches both the squeeze set and the state register, it is suppressed. Because it avoids regex compilation, dynamic memory allocations, and disk seeks, tr operates at near memory-bus speeds.
Under the hood, tr gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -d, -s, -c, -C, -t turns raw process and service tables into actionable diagnostics during incident response.
Availability and Installation Across Linux Distributions
The tr utility is packaged in coreutils across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether tr is installed and inspect which binary path and version your shell resolves:
type -a tr
tr --version 2>/dev/null || man -f tr
# Illustrative output (reviewed against documentation)
tr is /usr/bin/tr
tr (coreutils)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y coreutils
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y coreutils
# Arch Linux
sudo pacman -S --noconfirm coreutils
# Alpine Linux
sudo apk add --no-cache coreutils
Command Syntax, Arguments, and Exit Status Codes
tr [OPTIONS] SET1 [SET2]
The basic invocation syntax is tr [OPTIONS] SET1 [SET2]. SET1 defines the set of source characters to search for, and SET2 defines the corresponding replacement characters. Characters in SET1 are mapped one-to-one to characters in SET2 based on their ordinal position.
If SET2 is shorter than SET1, GNU tr automatically extends SET2 by repeating its final character until it matches the length of SET1, unless the -t (--truncate-set1) flag is supplied. Character sets can be defined using character ranges (e.g. 'a-z', '0-9'), POSIX character classes (e.g. '[:lower:]', '[:upper:]', '[:space:]'), or octal escape sequences (e.g. '\012' for newline).
0— Successful execution; byte stream translated or filtered without error.1— Operational failure; standard input read error or standard output write failure.2— Invalid command-line options, mismatched character sets, or malformed syntax.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-d | --delete | Delete characters in SET1; do not translate. |
-s | --squeeze-repeats | Replace each sequence of repeated characters in the final set with a single occurrence. |
-c, -C | --complement | Use the complement of SET1 (all characters except those in SET1). |
-t | --truncate-set1 | Truncate SET1 to the length of SET2 prior to translating. |
--help | --help | Display help documentation and exit. |
--version | --version | Output version information and exit. |
The combination of -c (--complement) and -d (--delete) is one of tr's most powerful idioms for data sanitization. For example, tr -cd '[:alnum:]\n' deletes every character that is NOT an alphanumeric letter or newline, stripping binary garbage, non-printable control characters, and rogue symbols from untrusted data.
Combining -d and -s is also common: tr -d '\r' deletes Windows carriage returns, while tr -s ' ' squeezes multiple consecutive spaces into a single space, allowing downstream commands like cut -d' ' to reliably parse space-delimited text.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Convert Text from Lowercase to Uppercase
Transform an incoming text stream to all uppercase letters using POSIX character classes.
echo "Production deployment initiated on server-01" | tr '[:lower:]' '[:upper:]'
# Illustrative output (reviewed against documentation)
PRODUCTION DEPLOYMENT INITIATED ON SERVER-01
tr maps every character in the [:lower:] set to its corresponding counterpart in the [:upper:] set.
2. Strip Windows Carriage Returns (CRLF to LF)
Remove \r carriage return characters from a script edited in Windows to make it runnable in Linux.
tr -d '\r' < windows_script.sh > linux_script.sh
file linux_script.sh
# Illustrative output (reviewed against documentation)
linux_script.sh: Bourne-Again shell script, ASCII text executable
The -d flag deletes every occurrence of \r without touching any other character in the stream.
3. Squeeze Consecutive Spaces into Single Spaces
Normalize ragged whitespace from ps command output to prepare it for delimiter-based tools.
ps -eo pid,user,comm | head -n 3 | tr -s ' '
# Illustrative output (reviewed against documentation)
PID USER COMMAND
1 root systemd
2 root kthreadd
The -s ' ' option replaces repeated space runs with a single space character.
4. Replace Delimiters (Colons to Tabs)
Convert colon-separated records from /etc/passwd into tab-separated values.
head -n 3 /etc/passwd | tr ':' '\t'
# Illustrative output (reviewed against documentation)
root x 0 0 root /root /bin/bash
daemon x 1 1 daemon /usr/sbin /usr/sbin/nologin
bin x 2 2 bin /bin /usr/sbin/nologin
tr substitutes every colon character (:) with a horizontal tab character (\t).
5. Sanitize Text: Keep Only Alphanumeric Characters
Strip punctuation, symbols, and formatting, preserving only letters, digits, and newlines.
echo "Order #8491-X (Approved!) $49.99" | tr -cd '[:alnum:] \n'
# Illustrative output (reviewed against documentation)
Order 8491X Approved 4999
The -cd flags complement the character set, deleting everything that is not an alphanumeric letter, space, or newline.
6. Convert Newlines to Commas (Flatten List)
Flatten a multi-line list of server hostnames into a comma-separated list.
cat << 'EOF' | tr '\n' ',' | sed 's/,$//'
node-01.infra
node-02.infra
node-03.infra
EOF
# Illustrative output (reviewed against documentation)
node-01.infra,node-02.infra,node-03.infra
tr replaces each newline (\n) with a comma, flattening vertical output into a single line.
Real-World Workflows, Pipelines, and Shell Automation
Cross-Platform Repository Cleaner: Automated CRLF Remediation
Sanitize shell scripts and configuration files committed with Windows line breaks across a project.
#!/usr/bin/env bash
set -euo pipefail
echo "Auditing shell scripts for DOS/Windows CRLF line endings..."
FOUND_DOS=0
while IFS= read -r file; do
if grep -q $'\r' "$file"; then
echo "Converting line endings: $file"
tr -d '\r' < "$file" > "$file.tmp" && mv "$file.tmp" "$file"
FOUND_DOS=$((FOUND_DOS + 1))
fi
done < <(find . -type f -name "*.sh")
echo "Remediation complete. Cleaned $FOUND_DOS files."
# Illustrative output (reviewed against documentation)
Auditing shell scripts for DOS/Windows CRLF line endings...
Converting line endings: ./scripts/deploy.sh
Converting line endings: ./scripts/backup.sh
Remediation complete. Cleaned 2 files.
Using tr -d '\r' with temporary files eliminates Windows line terminator bugs (\r\n) that break shell execution on Linux.
Secure Password and Random Token Generator
Generate high-entropy random alphanumeric passwords by filtering the kernel's urandom stream.
#!/usr/bin/env bash
set -euo pipefail
echo "=== Generated 24-Character Production Tokens ==="
for i in {1..3}; do
TOKEN=$(tr -dc 'A-Za-z0-9!@#%^&*' < /dev/urandom | head -c 24 || true)
echo "Token $i: $TOKEN"
done
# Illustrative output (reviewed against documentation)
=== Generated 24-Character Production Tokens ===
Token 1: 9xK#v8P@mQ2!wZ7^bL4&yT1*
Token 2: mB3#vF9@pL1!kX8^zR4&wQ5*
Token 3: kP7#wR2@mX9!bT4^yL8&zQ3*
tr reads raw binary bytes from /dev/urandom, discards non-matching characters with -dc, and head -c truncates to the desired token length.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding tr inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
tr reads strictly from stdin and writes to stdout. Never attempt to redirect output directly back into the source file (e.g. tr 'a' 'b' < file.txt > file.txt), as the shell will truncate file.txt to 0 bytes before tr reads it. Use a temporary file or sponge.
When generating random tokens or passwords from /dev/urandom using tr -dc, be aware that head -c sends SIGPIPE to tr upon reading the requested byte count. This is safe and expected behavior in Linux pipelines.
Be cautious when translating characters in security-sensitive files (such as /etc/passwd or /etc/shadow). Replacing or deleting characters improperly can alter user password hashes, lock root accounts, or corrupt user permission databases.
GNU/Linux, BSD, and BusyBox Implementation Differences
GNU coreutils tr operates on byte values. In standard GNU tr, multi-byte UTF-8 characters (such as emojis or accented characters like 'é') are treated as individual raw bytes, which can lead to invalid byte sequence corruption if multibyte characters are translated.
POSIX specifies tr behavior for single-byte character sets. BSD tr (on macOS and FreeBSD) and BusyBox tr (on Alpine Linux) adhere closely to standard POSIX behavior, supporting -d, -s, -c, and character classes, ensuring high script portability across platforms.
Troubleshooting Common Errors and Diagnostics
tr: extra operand 'file.txt'
Root Cause: A filename was passed as a command-line argument (e.g. tr 'a' 'b' file.txt). tr does not accept file arguments.
Resolution: Feed the file to tr using input redirection (<) or pipes (|).
# Incorrect:
tr 'a' 'b' input.txt
# Correct:
tr 'a' 'b' < input.txt
Garbled output when translating Unicode / UTF-8 characters
Root Cause: tr is a single-byte utility; multi-byte UTF-8 characters consist of 2 to 4 bytes, which tr attempts to translate byte-by-byte.
Resolution: Use sed or awk for multibyte UTF-8 string transformations.
# For UTF-8, use sed instead of tr:
sed 'y/éà/ea/' input.txt
Missing characters or unexpected translation mapping
Root Cause: SET2 is shorter than SET1 and -t was omitted, or character ranges were unquoted and expanded as shell file globs.
Resolution: Always quote character sets and ensure SET1 and SET2 have matching lengths.
tr '[a-z]' '[A-Z]' < file.txt
Alternatives, Related Commands, and Related Tutorials
- awk Command in Linux: Syntax, Text Patterns, and Field Processing — Practical syntax, flags, and examples for
awk. - Cut Command in Linux: Extract Columns, Fields, and Characters — Practical syntax, flags, and examples for
cut. - tee Command in Linux: Split and Redirect Streams with Examples — Practical syntax, flags, and examples for
tee. - sort Command in Linux: Sort Lines of Text and Numerical Data — Practical syntax, flags, and examples for
sort. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides



Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!