Text processing
rev
Reverse the characters of every line.
rev [OPTION...] [FILE...]
rev prints each line with its characters in reverse order; the order of the lines stays the
same (to reverse the lines, use tac). It is multi-byte aware, so accented letters survive.
Reversing text sounds like a toy, but it has one real job in pipelines: getting at the end of
a line when you don't know how many fields it has. rev | cut -d/ -f1 | rev takes the last
path component of any path, and the same trick gives the last field of any delimited line,
which plain cut cannot do.
Examples
Reverse each line
rev todo.txt
klim yub gub nigol xif stset etirw gub tuogol xif 4.2v yolped
Every line is mirrored, but buy milk is still the first line; only the characters within each line move.
Take the last field of each line
echo /var/log/demo/app.log | rev | cut -d / -f 1 | rev
app.log
cut can only count fields from the left. Reversing, taking field 1 and reversing back
yields the last field, app.log, however deep the path is.
Count email domains by their last part
tail -n +2 data/users.csv | cut -d , -f 3 | rev | cut -d . -f 1 | rev | sort | uniq -c
8 com
The third column is the email address. The reverse-cut-reverse trick pulls out the part
after the last dot, and all 8 users turn out to share com.
Check for a palindrome
for w in level shell racecar; do
[ "$w" = "$(echo "$w" | rev)" ] && echo "$w is a palindrome"
done
true
level is a palindrome racecar is a palindrome
A word equal to its own reversal is a palindrome; shell fails the test and prints nothing.
The final true keeps the loop's last failed test from becoming the exit status.
Multi-byte characters stay intact
echo 'naïve café' | rev
éfac evïan
rev reverses characters, not bytes, in a UTF-8 locale, so é and ï come out whole: éfac evïan.
Trap: Windows line endings move to the front
rev data/windows.txt | od -c | head -n 1
0000000 \r e n o e n i l \n \r o w t e
The carriage return is part of the line as far as rev is concerned, so it ends up as the
first character of each reversed line (\r e n o). Strip CRs first with tr -d '\r'.
Common pitfalls
revreverses characters within lines,tacreverses the order of lines. Mixing them up is the most common mistake.Carriage returns in CRLF files become the first character after reversing, which hides the start of the line on screen. Run
tr -d '\r'first.
GNU vs BSD and macOS
The examples above ran the GNU/Linux version. These are the differences that matter on macOS and the BSDs (written from their documentation, not run here).
On Linux
revcomes from util-linux; macOS has a BSDrevwith the same basic behaviour. Neither is in coreutils or POSIX.
Options worth knowing
A selection, described in our own words. For the full list, see rev(1) or rev --help.
| Option | What it does |
|---|---|
-0, --zero | Use NUL instead of newline as the line separator. |