Skip to content
Tutorials Center
My learning

Topics

Linux Command Reference ยท Text Processing

Linux rev command

Reference for the Linux rev command: reverse the characters of every line, use it to take the last field of a line, and how it differs from tac.

rev copies its input to standard output, reversing the order of the characters on every line. The lines themselves stay in the same order; to reverse the order of lines, use tac.

A palindrome check is the textbook use, but the practical one is a trick: reverse the line, cut the first field, and reverse again to get the last field of lines whose length varies, such as file paths.

Terminal
rev [FILE]...

Try it

Bash Reversing text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Bash The last-field trick

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Syntax

Terminal
rev [-0] [FILE]...
Option Description
FILE Files to read; with none, or - on some versions, standard input is read.
-0, --zero Newer util-linux only: lines end in NUL instead of newline.
-h, -V util-linux: help and version.

Returns: 0 on success, non-zero if a file cannot be opened.

Usage notes

  • Character-aware in UTF-8 locales. util-linux rev handles multi-byte characters, so รฉ stays intact; in the C locale it reverses bytes and breaks them. Combining accents attached to a letter may end up on the wrong letter.
  • Final newline: a line without a trailing newline is still reversed, and rev adds the newline.
  • Blank lines stay blank.
  • Last field of variable-length lines: rev | cut -d/ -f1 | rev works because the first field of the reversed line is the last field of the original. Prefer ${var##*/}, basename, or awk '{ print $NF }' when they fit; the rev trick is for shells without access to those.
  • Not a Unicode-aware grapheme reverser: emoji sequences and combined characters are reversed by code point.
  • Whole-file reversal (last line first, characters reversed too) is tac | rev.
  • Memory: rev processes one line at a time, so very long lines are the only memory concern.
  • Availability: part of util-linux on Linux and in the base system on BSD; it takes no options other than the file list on BSD.