Back to Explore
GuideVibeFix editorialUpdated Dec 2, 2026

tr From Zero: Translate, Delete, Squeeze — Three Jobs on a Stream of Characters

Uppercase a passage, strip the digits out of a phone number, squeeze five spaces into one, delete the carriage returns Windows left behind — tr does all of it one character at a time. This guide runs every command for real on GNU coreutils 9.4, including three measured findings: a short SET2 repeats its last character, complement deletion eats the newline too, and tr takes no filename at all.

Real close-up photograph of black computer keyboard keys with letters clearly visible (illustrative photo)

Everyone who has used a command line has done these little chores: turning a piece of text all uppercase, stripping the dashes and spaces out of a phone number, squeezing the run of several spaces in a log down to one, deleting the carriage return Windows left at the end of every line. They all have one thing in common: they change single characters, and they never touch the structure of the lines or the order of the words. Changing one character at a time is exactly tr's job. tr is one of the smallest tools in GNU coreutils: it reads a stream of bytes from standard input, writes a stream of bytes to standard output, and in between it does exactly three things — translate, delete, squeeze. This guide runs every command for real on coreutils 9.4: case conversion, deleting digits, squeezing spaces, keeping only digits, stripping carriage returns, ROT13 — plus three details the manual states only briefly and that only a real run makes obvious: a short second set repeats its last character, complement deletion eats the newline as well, and tr takes no filename at all — a filename is read as a third operand and errors out.

First, get tr's job straight. It works on a stream of characters, not on lines and not on files. Whatever bytes come in on standard input, it processes them one by one and writes them out on standard output. It does not understand regular expressions, it does not know what "line three" means, it does not cut columns, and it does not know filenames. Its whole skill set is three operations: translate, replacing characters from set 1 with the characters in the corresponding positions of set 2; delete, removing the characters in set 1 outright; squeeze, collapsing each run of the same repeated character into a single occurrence. The manual puts it in one sentence: tr copies standard input to standard output, performing one of translate, squeeze, delete, or delete-then-squeeze. Once "characters only, never lines" clicks, a lot of "why" questions answer themselves: why you cannot give tr a filename, why it cannot do sed's trick of replacing foo with bar on line three, and why squeezing spaces never deletes the single space between two words.

The most common use is translation: case conversion. The real run: echo 'Hello Vibe' | tr 'a-z' 'A-Z' prints HELLO VIBE; the other way round, echo 'Hello Vibe' | tr 'A-Z' 'a-z' prints hello vibe. The form is tr set1 set2: the first character of set 1 becomes the first character of set 2, the second becomes the second, and so on. a-z is range notation for all lowercase letters from a to z; A-Z is the same for uppercase. There is a sturdier spelling that uses character classes: echo 'Hello Vibe' | tr '[:lower:]' '[:upper:]' prints HELLO VIBE as well. A character class is a name between [: and :], so [:lower:] means all lowercase letters and [:upper:] means all uppercase letters. Case conversion is tr's bread and butter — eight times out of ten in a script, that is why it is there: lowercasing logs before grepping them, uppercasing filenames before archiving them, normalising user input regardless of the case it was typed in.

The syntax of sets is worth spelling out, because it is the whole of tr's grammar. The most direct form is listing characters one by one: tr 'aeiou' '12345' turns a into 1, e into 2, i into 3, o into 4, and u into 5. Next come ranges: a-z, A-Z, 0-9, each expanding to every character from the start to the end in order. Third come character classes: [:alnum:] is letters and digits, [:alpha:] is all letters, [:digit:] is all digits, [:space:] is all whitespace — space, tab, newline included — [:punct:] is all punctuation, [:lower:] and [:upper:] are the two cases, [:xdigit:] is hexadecimal digits, [:blank:] is horizontal whitespace, [:cntrl:] is control characters, [:graph:] and [:print:] are printable characters. Then there are the escapes: \n is newline, \t is tab, \r is carriage return, \\ is backslash, and \NNN is the character with that octal value. Always quote character classes: write tr '[:lower:]' '[:upper:]'. Without quotes, the shell expands [:lower:] as a glob pattern against the filenames in the current directory first; if nothing matches you get lucky and it passes through unchanged, but if something does match, the command quietly becomes something else — the hardest kind of bug to find, because the command itself never errors.

When set 1 and set 2 are different lengths, tr has a rule of its own, and a real run shows it best. echo 'abcdef' | tr 'a-z' 'XY' prints XYYYYY: set 1 is the 26 lowercase letters, set 2 has only X and Y, so a becomes X and everything from b to z becomes Y. The manual's own words: ARRAY2 is extended to length of ARRAY1 by repeating its last character as necessary — when set 2 is too short, its last character is repeated to pad it out. Now add -t: echo 'abcdef' | tr -t 'a-z' 'XY' prints XYcdef. -t is --truncate-set1: it first cuts set 1 down to the length of set 2, so only a and b are translated to X and Y, and c through f are not in the set at all and pass through unchanged. Put the two results side by side and the difference is clear: without -t, the short set 2 gets stretched; with -t, the long set 1 gets cut. Beginners trip here more than anywhere else: they write tr 'a-z' 'XY' meaning to translate two letters, and the whole alphabet comes out as Y — the command is not wrong, that is simply the rule.

Deletion is the most straightforward of the three: -d (--delete) removes the characters in set 1 and translates nothing. The real run: echo 'call 555-1234 now' | tr -d '0-9' prints call - now — the digits are gone, the dash and the spaces remain; echo 'a b c d' | tr -d ' ' prints abcd, the spaces all gone. Note that -d only looks at set 1; there is no set 2 to give, and giving one does nothing — the manual says delete characters in ARRAY1, do not translate. Deleting characters looks trivial, but it earns its keep: dashes and spaces mixed into phone numbers and order numbers, stray punctuation in logs, odd characters picked up by copy and paste — all of them are one tr -d away. Think of delete and translate as a pair: first decide "which characters do I not want at all", that is the set for -d; then decide "which characters should become what", those are the two sets for translation. Only one operation happens per call; if you want both, chain them with a pipe.

Deleting carriage returns is -d's classic real-world job: a text file carried over from Windows has a \r (carriage return) at the end of every line, which shows up on Linux as a ^M at the end of each line. The real run: printf 'a\r\nb\r\n' | tr -d '\r' | od -c prints 0000000 a \n b \n, then 0000004. od -c reads the bytes out one by one: after processing, only a, newline, b, newline remain, and the \r bytes are gone. \r is written as '\r' in tr, one of the escape sequences the manual lists. The one-liner tr -d '\r' is standard equipment for cross-platform work: run a .csv, .txt, or log file from Windows through it before handing the file to anything else, or grep, awk, and cut will all be tripped up by the invisible \r at the end of each line — the usual symptoms are a last column from cut that ends in \r, or a variable in a script whose value carries an invisible character at the end, so a comparison never matches.

The complement is the option people misuse most: -c (--complement) means use not the set you gave, but its complement — every character you did not list. The real run: echo 'order 42 ships in 3 days' | tr -cd '[:digit:]' prints 423. -c turns the set inside out: delete "everything that is not a digit", keeping only the digits. It looks handy, and it is — but the run has a detail worth noticing: the output is 423 and then the rc=0 note lands on the same line, because the newline \n is not in the digit set either, so it was deleted too, and the output ends with no newline. To keep the newline, list it as well: echo 'order 42 ships in 3 days' | tr -cd '[:digit:]\n' prints 423 followed by a newline. The conclusion fits in one sentence: complement deletion deletes "everything not listed", and the newline is part of "everything" unless you list it yourself. When a script extracts digits or letters, miss this detail and the output glues itself to the next shell prompt, looking in the log as if a line went missing.

Squeezing is the third operation: -s (--squeeze-repeats) collapses each run of the same character into a single occurrence. The real run: echo 'a b c d' | tr -s ' ' prints a b c d — two spaces collapse to one, three spaces collapse to one, and a single space is left alone. printf 'one\n\n\n\ntwo\n' | tr -s '\n' prints one and two on their own lines, the three blank lines in between squeezed to one. Note the difference between squeeze and delete: -s ' ' never removes spaces, it only collapses "several in a row" into one; the single space between two words stays exactly where it was. The set after -s says "which characters do this collapsing to" — repeats of characters outside the set are left alone: echo 'MISSISSIPPI' | tr -s 'S' prints MISISIPPI, only the S was squeezed, the repeated I is still there. The most common use is tidying format: spaces that do not line up in a log, extra blank lines in a file, runs of whitespace picked up by copy and paste — one tr -s sorts them out.

Translation and squeezing can happen in a single call, and the order is fixed: translate (or delete) first, squeeze second. The real run: echo 'aaabbbccc' | tr -s 'a-z' prints abc — first the translation step (here there is no second set, so only squeezing applies), then each run of a, b, and c collapses to one. The manual's own words: squeezing occurs after translation or deletion. Once you know the order, the set after -s reads correctly: it means "in the result after translation or deletion, squeeze these characters" — not "in the input". Delete and squeeze can also be combined in one call: with -d and -s together, delete set 1 first, then squeeze set 2. The real run: printf 'aaa bbb ccc\n' | tr -ds 'a' ' ' prints " bbb ccc" — first all the a's are deleted, leaving " bbb ccc", then the runs of spaces collapse to one. That combination is handy when cleaning text: remove one class of characters, then tidy in one pass the runs of whitespace left behind by the removal.

ROT13 is the best demonstration of translation: rotate the alphabet by half, a becomes n, b becomes o, and so on, and translating twice brings you back. The real run: echo 'Hello Vibe' | tr 'a-zA-Z' 'n-za-mN-ZA-M' prints Uryyb Ivor; translate once more, echo 'Uryyb Ivor' | tr 'a-zA-Z' 'n-za-mN-ZA-M', and it prints Hello Vibe, exactly as it started. The sets are worth a look: 'a-zA-Z' is lowercase a to z plus uppercase A to Z, and 'n-za-mN-ZA-M' is n to z, a to m, N to Z, A to M — 52 characters on each side, matched position by position. ROT13 is not encryption, only the alphabet rotated by half; forums used to use it to hide spoilers and answers. Its value here is as a demonstration: tr's translation is strictly positional, the nth character of set 1 becomes the nth character of set 2, with no exceptions and no character treated as special. One small detail about the hyphen: at the start or the end of a set it means itself — tr -d '-' deletes hyphens — and only between two characters, as in a-z, does it mean a range. Where you put the hyphen decides whether it is a range or just itself.

When tr's output looks wrong, the fastest way to see what actually happened is od -c, which reads the bytes out one by one instead of letting the terminal interpret them. That is how the carriage-return demo above was verified: printf 'a\r\nb\r\n' | tr -d '\r' | od -c printed a, newline, b, newline, and nothing else — the \r bytes visibly gone, rather than invisibly absent. od -c is also the tool for the case that confuses everyone exactly once: output that looks right on screen but fails every comparison. A trailing \r, a trailing space, a tab where you expected a space — all of them are invisible in a terminal and obvious in od -c output, where each byte gets its own column. The habit to build is: whenever a tr pipeline produces something surprising, stick | od -c on the end before changing the tr command. Nine times out of ten the command was fine and the input had a byte you could not see; the tenth time, od -c shows you exactly which byte tr produced that you did not expect, and the fix writes itself.

The biggest trap in tr, and the one every beginner hits on the first try, is that it takes no filename. The real run: echo 'Hello' | tr 'a-z' 'A-Z' hello.txt prints tr: extra operand 'hello.txt', followed by Try 'tr --help' for more information, with exit code rc=1. The synopsis in the manual is unambiguous: tr [OPTION]... STRING1 [STRING2] — the operands are two strings, and there is no place for a file. Hand it a filename and tr reads it as a third operand and errors out. There are two correct forms: a redirect, tr 'a-z' 'A-Z' < hello.txt, which prints HELLO VIBE; or a pipe, cat hello.txt | tr 'a-z' 'A-Z'. Why does tr not take a filename? Because it is designed as a filter: standard input in, standard output out, one link in a Unix pipeline. grep, sed, and awk all accept a filename directly; tr alone does not. Remember that one exception and you save yourself a round of "why is this erroring" debugging.

Sets have two repeat spellings, written in the manual and rarely used day to day, but worth explaining once. The first is [CHAR*], meaningful only in set 2: it means "repeat CHAR until set 2 is as long as set 1". For example, tr 'a-z' '[x*]' turns all 26 lowercase letters into x — the same result as tr 'a-z' 'x', because a short set 2 repeats its last character anyway; [x*] only writes that rule out in the open. The second is [CHAR*REPEAT], meaning "CHAR repeated REPEAT times", with REPEAT in octal: tr 'a-z' '[x*5]' is a set 2 of five x's. Octal escapes \NNN belong to the same family: \000 is the null byte, \007 is the bell, \011 is the tab — tr works byte by byte, so it recognises even "invisible" characters like \0. When would you use these? Handling binary data or text carrying null bytes: tr -d '\000' deletes the null bytes from a file, which od -c confirms at a glance. Everyday text work never needs these spellings, but knowing the manual has them means you will not mistake [CHAR*REPEAT] for a typo the day you come across it.

The full table of character classes is worth listing once, so you never have to look it up mid-task: [:alnum:] is letters and digits, [:alpha:] is all letters, [:blank:] is horizontal whitespace (space and tab), [:cntrl:] is control characters, [:digit:] is digits, [:graph:] is printable characters not including space, [:lower:] is lowercase letters, [:print:] is printable characters including space, [:punct:] is punctuation, [:space:] is all whitespace, horizontal and vertical, including newlines, [:upper:] is uppercase letters, and [:xdigit:] is hexadecimal digits. There is also the equivalence class spelling [=CHAR=], meaning all characters equivalent to CHAR — almost never used day to day, but it exists. In practice three groups cover nearly everything: case conversion with [:lower:] and [:upper:], deleting digits with [:digit:], and deleting whitespace with [:space:]. The advantage of a class over hand-writing a-z is portability: in some locales a-z may expand in an order you did not expect, while [:lower:] always means "all lowercase letters" and never changes its meaning.

Locale is the subject of a whole BUGS section in the tr manual, and it deserves a careful read: Full support is available only for safe single-byte locales, in which every possible input byte represents a single character. The C locale is safe in GNU systems, so you can avoid this issue in the shell by running LC_ALL=C tr instead of plain tr. In plain language: tr's support for multibyte characters — Chinese characters, for example — is incomplete, and it is only fully reliable in the single-byte C locale. In a UTF-8 environment, plain ASCII work like tr 'a-z' 'A-Z' is completely fine; but if you point tr at Chinese text, or use ranges that touch non-ASCII characters, the result may not be what you expected. The safe habit is: use it directly for English, digits, and punctuation, and as soon as multibyte characters are involved, prefix the command with LC_ALL=C, as in LC_ALL=C tr 'a-z' 'A-Z'. You will never feel this detail in daily use; it only surfaces when you process Chinese logs or Chinese filenames — and when it does, check the locale before doubting your sanity.

Finally, a few recipes ready to use as they are. First, normalise a log before searching it: cat app.log | tr 'A-Z' 'a-z' | grep 'error' — whether the log writes Error, ERROR, or error, lowercasing first catches them all in one grep. Second, pull the digits out of mixed text: echo 'order 42 ships in 3 days' | tr -cd '[:digit:]\n' prints 423 — order numbers, quantities, and the digits inside dates come out in one line, and remember to list \n in the set or the output glues itself to the next line. Third, strip carriage returns from a Windows file before processing it: tr -d '\r' < win.csv > unix.csv — with the \r gone, cut and awk stop being tripped up by the invisible character at the end of each line. Fourth, clean text before counting words: tr -d '[:punct:]' < article.txt | tr 'A-Z' 'a-z' | tr -s ' ' — punctuation deleted, case unified, spaces squeezed — and then sort, uniq, and wc see clean words. Fifth, check a file for strange whitespace hiding inside it: cat file.txt | tr -d '[:print:]\n' | od -c shows the non-printable characters at a glance. None of these is tr working alone — tr is always one link in a pipeline, with input in front of it and the next tool behind it.

One pipeline deserves to be worked through end to end, because it shows tr doing three jobs in a row with three different tools behind it: counting word frequencies. Take the sentence "The cat sat on the mat. The cat sat." First, tr -d '[:punct:]' deletes the full stop, leaving "The cat sat on the mat The cat sat". Next, tr 'A-Z' 'a-z' lowercases everything, so "The" and "the" stop being two different words. Then tr ' ' '\n' turns every space into a newline, putting one word on each line — this is the step people forget, and without it sort and uniq see one long line instead of words. Finally, sort | uniq -c | sort -nr counts the identical lines and orders them: the appears 3 times, sat 2, cat 2, on 1, mat 1. The whole pipeline is echo 'The cat sat on the mat. The cat sat.' | tr -d '[:punct:]' | tr 'A-Z' 'a-z' | tr ' ' '\n' | sort | uniq -c | sort -nr, and every stage does exactly one thing: tr cleans, sort orders, uniq counts. Run it on a real article instead of a toy sentence and you get a frequency table good enough to spot the words a text leans on — which is, incidentally, how the recipes paragraph above was checked before it was written.

Five traps beginners fall into, collected here in one place. First, passing tr a filename: it takes no file, the filename is read as a third operand and errors out with rc=1 — use a redirect or a pipe. Second, leaving a character class unquoted: tr [:lower:] [:upper:] lets the shell expand [:lower:] as a glob first, and the meaning of the command changes — always single-quote character classes. Third, thinking tr edits files in place: it does not, it only writes to standard output — to change a file, redirect to a temporary file and move it back, as in tr -d '\r' < a.txt > a.tmp && mv a.tmp a.txt. Fourth, thinking -s deletes: tr -s ' ' never removes spaces, it only squeezes runs of spaces into one — to remove them entirely, use -d. Fifth, thinking tr understands regular expressions or lines: it does not — tr 'foo' 'bar' is not "replace foo with bar", it is f becomes b, o becomes a, and the second o becomes r, each character translated on its own. And one more basic point: tr does one thing per call — translate, delete, or squeeze, or delete-plus-squeeze — and for more than that, chain several tr calls with pipes, or hand the job to sed or awk.

To keep this guide from repeating ones already published, here are the boundaries. sed and awk are the other two of the Unix text trio: sed replaces by line, can address a specific line, and understands regular expressions; awk cuts by column, can do arithmetic, and can write conditions — tr does none of that, it only translates, deletes, and squeezes characters. The division of labour fits in one sentence: to change a character, reach for tr; to change a line or a passage, reach for sed; to work by column, calculate, or apply conditions, reach for awk. grep is "find lines by content" while tr is "change content by character" — one finds, the other changes, and they often sit in the same pipeline, grep finding the lines first and tr normalising them second. cut is "cut fields by column" while tr is "change content by character" — one cuts columns, the other changes characters. sort plus uniq is "deduplicate lines" while tr -s is "deduplicate characters" — one minds lines, the other minds characters. Each guide minds its own patch, and together they add up to complete text processing.

By now you have one more small, fast blade in hand: without opening an editor, without writing a script, a single command flips the case of a passage, pulls the digits out, squeezes the extra spaces and blank lines away, and strips the carriage returns Windows left behind. Its rules are only three: it recognises characters, never lines; it reads standard input only, never a filename; and a short set 2 repeats its last character. A good way to keep the three rules straight is to remember the pipeline shape — something | tr ... | something — because tr never opens a file, never prints a filename, and never sees a line, only the stream passing through it. The next time pasted text arrives with its formatting in a mess, do not reach for the editor and fix it by hand — first ask whether one line of tr would tidy it up. Eight times out of ten, the answer is yes. Run the demo in this guide yourself — translate ROT13 twice, eat a newline with a complement set once, and pass a filename as an operand and watch it error — and those three rules will stop being sentences in a manual and become experience of your own.

tr does three things: translate, delete, squeeze

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photograph of a magnifying glass resting on a stack of paper documents on a wooden desk (illustrative photo)
Guide
stat From Zero: Read a File's Identity Card and Its Four Timestamps

ls shows you one short line per file. stat reads out the whole record: size, blocks, inode, permissions, owner, and four timestamps that each move for a different reason. This guide runs every command for real on GNU coreutils 9.4 — including the measured finding that chmod moves ctime and leaves mtime alone, and that --printf prints no trailing newline.

Developer WorkflowTool TipsLearning & Career
Real photograph of a fingertip with a glowing fingerprint pattern overlaid (illustrative photo)
Guide
sha256sum From Zero: Give Every File a Fingerprint, Then Verify It Before You Trust It

Downloaded an installer or a model weights file — how do you know it arrived intact? sha256sum computes a 64-hex fingerprint for any file: change one byte and the fingerprint changes completely. This guide runs every command for real on GNU coreutils 9.4: fingerprints, manifests, bulk checks, deliberate tampering, a missing file, quiet mode — plus the measured finding that --ignore-missing skips missing files, not mismatched ones.

Developer WorkflowTool TipsLearning & Career
Real photograph of a monitor showing a multi-pane terminal with system logs in a dark room (illustrative photo)
Guide
watch From Zero: Run a Command Every Few Seconds and Watch the Screen for Changes

Waiting for a build, a log, a status flip — much of the time you don't need a script, just one command that re-runs every few seconds and pins the result to the screen. This guide runs every watch command for real on procps-ng 4.0.4: the default interval, the header, -d highlighting, -g stop-on-change, -q stop-on-unchanged, -e freeze-on-error — plus the measured finding that -e's exit code is always 8, whatever the manual promises.

Developer WorkflowTool TipsLearning & Career