← Full reference

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

InputOutputComment
helloollehcharacters in reverse order
a<TAB>bb<TAB>aa tab is an ordinary character
x\r (a line from Windows)\rx\r moves to the start of the line
abc without a trailing \ncba without \nno newline is added
äöüüöäonly in a UTF-8 locale (see pitfalls)

Tricks

TaskCommand
last fieldrev | cut -d/ -f1 | rev
everything but the last fieldrev | cut -d. -f2- | rev
last N characters of a linerev | 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 utilitiestr ' ' '\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 C locale rev hangs on non-ASCII text. The sandbox's default locale is C, and echo café | rev doesn't finish until you interrupt it with Ctrl+C. For accented letters and any UTF-8 run LC_ALL=C.UTF-8 rev.
  • rev reverses characters, not words. echo 'one two' | rev gives owt eno. To change the order of fields, use awk or a tr/tac/paste chain.
  • rev doesn't change the order of lines — that's tac (see cat and tac).
  • A \r at the end of a line moves to the start. Strip \r from Windows files first (tr -d '\r'), otherwise after a double rev and cut an invisible \r ends 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. The rev trick is useful when you specifically need cut with its ranges (-f2-).

See also

cut · cat and tac · awk · tr · paste