rev
Reverse each line character by character; the "last field" trick and reversing field order
rev reverses each line character by character: hello → olleh. The order of lines doesn't change (that's what tac is for). On its own rev is rarely needed, but paired with cut it solves a common task — taking the last field when the number of fields isn't known in advance.
Syntax
rev [file…]
Without files it reads standard input. There are practically no working options: only -h (help) and -V (version). rev is part of util-linux.
What gets reversed
| Input | Output | Comment |
|---|---|---|
hello | olleh | characters in reverse order |
a<TAB>b | b<TAB>a | a tab is an ordinary character |
x\r (a line from Windows) | \rx | \r moves to the start of the line |
abc without a trailing \n | cba without \n | no newline is added |
äöü | üöä | only in a UTF-8 locale (see pitfalls) |
Tricks
| Task | Command |
|---|---|
| last field | rev | cut -d/ -f1 | rev |
| everything but the last field | rev | cut -d. -f2- | rev |
| last N characters of a line | rev | cut -c1-N | rev |
| fields in reverse order (not characters!) | awk '{for(i=NF;i>0;i--) printf "%s%s", $i, (i>1?OFS:ORS)}' |
| words in reverse order using standard utilities | tr ' ' '\n' | tac | paste -sd' ' |
Examples
# reverse a string
echo 'hello' | rev
# file name from a path — the last field
echo /var/log/nginx/access.log | rev | cut -d/ -f1 | rev
# path without the file name
echo /var/log/nginx/access.log | rev | cut -d/ -f2- | rev
# strip the last extension
echo backup.tar.gz | rev | cut -d. -f2- | rev
# last 4 characters of each line
printf '2026-10-13\n2025-01-01\n' | rev | cut -c1-4 | rev
# fields in reverse order — a job for awk, not rev
echo 'one two three' | awk '{for(i=NF;i>0;i--) printf "%s%s", $i, (i>1?OFS:ORS)}'
# the same via tr, tac and paste (one line of input)
echo 'one two three' | tr ' ' '\n' | tac | paste -sd' '
# is the string a palindrome
s=level; [ "$s" = "$(echo "$s" | rev)" ] && echo palindrome
# accented letters — only with a UTF-8 locale
echo 'café' | LC_ALL=C.UTF-8 rev
Pitfalls
- In the
Clocalerevhangs on non-ASCII text. The sandbox's default locale isC, andecho café | revdoesn't finish until you interrupt it with Ctrl+C. For accented letters and any UTF-8 runLC_ALL=C.UTF-8 rev. revreverses characters, not words.echo 'one two' | revgivesowt eno. To change the order of fields, use awk or atr/tac/pastechain.revdoesn't change the order of lines — that'stac(see cat and tac).- A
\rat the end of a line moves to the start. Strip\rfrom Windows files first (tr -d '\r'), otherwise after a doublerevandcutan invisible\rends up at the start of the value. - There are simpler ways to get the "last field".
awk -F/ '{print $NF}',basename,${path##*/}in bash read better. Therevtrick is useful when you specifically need cut with its ranges (-f2-).
See also
cut · cat and tac · awk · tr · paste