Website Vidya
Cloud & DevOpsStep-by-Step Guide

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.

RR
Rajesh RayLead Systems Educator
Published:
9 min read
PDF Cheat Sheet
tr Command in Linux: Translate, Delete, and Squeeze Characters
AI Executive SummaryWebsiteVidya AI

9 min read

Learn tr command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What tr Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

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.

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.

Advertisement
tr Command in Linux: Translate, Delete, and Squeeze Characters — syntax, flags, and practical terminal workflow diagram
tr Command in Linux: Translate, Delete, and Squeeze Characters — command syntax, key options, and production workflow reference.

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:

Advertisement

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 / FlagLong Form / ArgumentTechnical Behavior and Purpose
-d--deleteDelete characters in SET1; do not translate.
-s--squeeze-repeatsReplace each sequence of repeated characters in the final set with a single occurrence.
-c, -C--complementUse the complement of SET1 (all characters except those in SET1).
-t--truncate-set1Truncate SET1 to the length of SET2 prior to translating.
--help--helpDisplay help documentation and exit.
--version--versionOutput 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.

Advertisement

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

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

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
tr was designed according to the Unix filter philosophy: perform one stream transformation task with maximum performance. Reading exclusively from standard input avoids file-handling overhead and allows seamless piping between commands.
Run tr -d ' ' < file.txt > output.txt to delete all spaces, or tr -d '[:blank:]' to delete both spaces and horizontal tabs.
The -s flag replaces consecutive occurrences of a specified character with a single instance. For example, echo 'hello world' | tr -s ' ' outputs 'hello world'.
Run tr 'A-Za-z' 'N-ZA-Mn-za-m' < file.txt. Each letter is rotated 13 positions through the alphabet, creating a reversible substitution cipher.
RR
Written byVerified Author

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.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Cloud & DevOps•

How to Close File Descriptors Above 9 in Dash Shell

Attempting to close a file descriptor above 9 in Dash using exec 10<&- results in a 10: not found error because Dash's POSIX lexer only recognizes single-digit file descriptors (0–9) in redirection operators. This guide explains the exact parser limitation, why FDs 10+ are reserved for internal shell state, and how to safely close inherited file descriptors using close_range, Python, or Perl wrappers.

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout