Linux rev Command: Reverse Text One Line at a Time
Learn to reverse characters line by line with Linux rev, use files and pipelines safely, and handle Unicode, CRLF endings, and output redirection.
The Linux rev command reverses characters within each input line. It reads a line, writes that line from right to left, then starts the next line. Newline characters remain separators, so rev does not turn a multiline file upside down. It also does not split text into words and rearrange the words.
That distinction makes rev useful in pipelines, quick text transformations, and shell experiments. It is a filter: input comes from named files or standard input, and transformed text goes to standard output. The util-linux rev manual describes it as “reverse lines characterwise” and notes that it buffers a whole wide-character line in memory.
Check which rev implementation you have
This tutorial uses Linux syntax and a normal text terminal. On many Linux systems, rev comes from util-linux. Check your installation before relying on implementation-specific options:
command -v rev
rev --version
With util-linux, the second command prints a version such as rev from util-linux 2.39.3. BSD/macOS implementations may differ; do not assume that --version or every option shown here exists there. If the command is absent, use your distribution’s package documentation to identify the package supplying it. Package names and administrator policies vary.
Reverse text from standard input
The quickest way to try the command is to pipe quoted text into it:
printf '%s\n' 'stressed' 'red blue' | rev
Output:
desserts
eulb der
Each line is handled independently. The space in red blue is a character too, so it changes position along with the letters. The result is not blue red: that would require reversing word order while leaving each word’s spelling intact.
Use printf with a fixed format and quoted arguments when exact characters matter. Single quotes are useful for literal sample strings because they prevent shell expansion of dollar signs, wildcards, and other special characters. Quote filenames too; double quotes are appropriate when you intentionally need a variable to expand.
For interactive input, run:
rev
Type a line and press Enter; its reversed version appears while the program continues waiting for input. When finished, signal end-of-file with Ctrl-D on an empty input line. If text has not ended with Enter, Ctrl-D may first deliver that pending text, requiring a second press to end input. A pipe is usually clearer for repeatable examples:
printf '%s\n' 'Linux' 'one line at a time' | rev
Output:
xuniL
emit a enil eno
Punctuation, spaces, and blank lines
Reversal is characterwise, not alphabetic. Leading spaces become trailing spaces, punctuation changes position, and an empty line remains empty:
printf '%s\n' '' ' hi! ' | rev
The output starts with a blank line. The second line contains two spaces, !ih, and two more spaces. This deliberately symmetric padding stays at both ends, although the characters inside it reverse. Use an asymmetric example to see spaces move more clearly:
printf '%s\n' ' ab ' | rev
The result is one space, ba, and two spaces. The command does not trim whitespace, normalize punctuation, or fix spelling. It reverses the order of text characters; it does not horizontally flip the shapes of printed letters like a mirror-image graphic.
A newline separates lines rather than becoming one of their reversed characters. For ordinary newline-terminated input, the same line boundaries remain. With input that has no final newline:
printf '%s' 'abc' | rev
The util-linux 2.39.3 version used to check these examples returns cba without adding a newline. That can leave the next shell prompt immediately beside the output. If you require a final newline, supply one intentionally with printf '%s\n'. Check your own implementation before depending on byte-for-byte line-ending behavior.
Reverse a file without changing the source
Give an existing text filename as an argument to write its reversed content to standard output. Replace this sample path with the file you intend to read:
rev './sample.txt'
The source is read, not edited in place. Prefixing a relative filename with ./ is useful when its name begins with a hyphen, because it prevents the name from looking like an option. For example, rev './-notes.txt' reads a file in the current directory.
To save a separate result, redirect standard output to a different path:
rev './sample.txt' > './sample.reversed.txt'
This leaves the source unchanged but creates or replaces the destination. Bash’s redirection documentation explains that > creates a missing file and truncates an existing regular file before the command runs.
Never use rev './sample.txt' > './sample.txt'. The shell opens the output before rev can read the input, destroying the source contents. Different path spellings are not enough if they refer to the same file through a link. Choose a genuinely separate destination and keep the original until you have reviewed the result.
If accidental overwrite is a concern, Bash’s noclobber option can reject an existing destination. A subshell confines the setting to this operation:
( set -o noclobber; rev './sample.txt' > './sample.reversed.txt' )
With an existing regular output file, that redirection fails instead of truncating it. This is a shell feature, not a special rev option, and it is not a substitute for choosing distinct input and output files.
Check success before taking any later action:
if ( set -o noclobber; rev './sample.txt' > './sample.reversed.txt' ); then
printf '%s\n' 'Reversal completed.'
else
printf '%s\n' 'Reversal failed; inspect the error.' >&2
fi
A nonzero status can mean an unreadable input, a refused output path, or a processing error. Do not automatically replace the original just because an output file exists; it might be empty or incomplete.
rev versus tac: characters or lines?
The names are easy to confuse, but the operations differ:
printf '%s\n' 'first' 'second' | rev
Output:
tsrif
dnoces
To reverse the order of whole lines, use tac instead:
printf '%s\n' 'first' 'second' | tac
Output:
second
first
The GNU tac manual describes reversing records, which are lines by default. GNU tac is not installed on every operating system. A file needing both transformations can pass through both filters: tac './sample.txt' | rev puts the last line first and reverses the characters inside each resulting line. For line-order tasks and alternatives, see the reverse line order guide.
Extract a final field with a small pipeline
Because rev reads standard input and writes standard output, it composes with other Unix filters. This example extracts text after the last colon:
printf '%s\n' 'alpha:beta:gamma' | rev | cut -d ':' -f 1 | rev
Output:
gamma
The first reversal produces ammag:ateb:ahpla; cut selects the first colon-delimited field, ammag; the final reversal restores gamma. The same logic works for each newline-separated input record.
Define your edge cases before reusing the pattern. With no colon, cut passes the line through by default, so the two reversals return the original string. A final colon produces an empty final field. That may be correct for your data, or it may need explicit validation.
This is a simple delimiter transformation, not a CSV parser. Quoted delimiters, escaped characters, and fields containing embedded newlines need a format-aware tool. For a complicated data format, a clever pipeline is not automatically clearer or safer than a proper parser.
Verify a transformation with double reversal
Reversing twice restores ordinary text when the line handling and encoding remain consistent:
printf '%s\n' 'hello' 'two words' | rev | rev
Output:
hello
two words
For a file, keep the original and save each stage under a distinct, unused name. Compare the twice-reversed result with the original using cmp for byte comparison. Use diff -u when you want a readable, line-oriented comparison. A difference is a reason to inspect line endings and encoding, not to discard the original.
Also check simple invariants: the first input line should still correspond to the first output line, empty lines should stay in their positions, and no unexpected filename headers should appear. When several input files are supplied, rev writes their transformed contents consecutively; it does not create separate output files or insert file-boundary labels.
Unicode, tabs, and Windows line endings
Modern util-linux rev works with wide-character lines under the active locale. “Character” does not necessarily mean a user-perceived grapheme cluster. Try an explicit UTF-8 locale only if that locale is available on your system:
printf '%s\n' 'café' '👨👩👧👦' | LC_ALL=C.UTF-8 rev
With a suitable UTF-8 environment, the first result is éfac. A joined family emoji can become a visually surprising sequence because it contains several code points and zero-width joiners. Reversal does not preserve every grapheme cluster. Combining marks are another reason visually equivalent strings can behave differently. For an approach designed around grapheme boundaries, compare the JavaScript Unicode reversal guide.
Tabs move like other characters, but their displayed width depends on their new position. Windows-style CRLF endings need special care: the carriage return is not removed automatically. Under the tested util-linux implementation, input bytes represented as abc\r\n become \rcba\n. The carriage return now precedes the letters and can make terminal output misleading. Normalize line endings separately when appropriate; do not silently strip meaningful data.
Avoid rev for binary data, encryption, or protecting secrets. Reversal is easy to undo. The manual also notes that a complete wide-character line is buffered in memory: a huge file with no line breaks can require a large allocation or fail. Line-oriented processing does not mean constant memory for arbitrarily long lines.
Troubleshooting and a safe checklist
If the command waits without printing anything, it may be expecting input rather than hanging. Supply a file, pipe text into it, or finish interactive input with a newline and then end-of-file. If output looks unchanged, check whether the line is empty, contains one character, or is a palindrome. Also confirm you expected character reversal rather than line-order reversal.
Use rev --help to inspect the options supported by your installed version. Newer util-linux documentation may show features absent from older packages; do not assume a zero-terminated-record option exists everywhere just because a current manual mentions it.
Before using a pipeline on valuable text:
- Confirm whether you need characters, words, or complete lines reversed.
- Try a small quoted sample with a known result.
- Choose a separate, unused output path.
- Inspect command status and the generated text.
- Test Unicode and line endings that occur in your actual data.
For a quick individual sample without a terminal, the Text Reverser tool offers a browser-based alternative. For local files and repeatable shell pipelines, rev is useful precisely because its job is small: reverse characters one line at a time, with explicit choices about input, output, and encoding.
Try the Text Reverser tool
Reverse text, words, or letters instantly — free and entirely in your browser.
Open the tool