How to Use the rev Command to Reverse Text in Linux

Linux is packed with highly specialized command-line tools that perform exactly one job perfectly. While commands like grep or awk handle complex text parsing, the rev command has a much simpler, albeit unusual, purpose: it takes a string of text and completely reverses the order of the characters on a line-by-line basis. While this might sound like a parlor trick, rev is surprisingly useful when combined with other tools in a bash pipeline to manipulate file extensions or parse logs from right to left.

Basic Usage: Reversing a File

If you execute the rev command and point it at a standard text file, it will print the contents of the file to the terminal, but the characters on every single line will be flipped backward.

For example, assume you have a file named names.txt containing the following:

Alice
Bob
Charlie

Running the command:

rev names.txt

Will output:

ecilA
boB
eilrahC

Reversing Standard Input via Pipes

Like all good UNIX utilities, rev can accept standard input via a pipe (|). This allows you to reverse the output of other commands on the fly.

echo "Hello World" | rev

Output: dlroW olleH

Practical Application: Parsing from Right to Left

The most common real-world use case for rev involves extracting data from the end of a string when the length of the string is unpredictable. The standard cut command only parses from left to right. If you want to extract the file extension from a long, complex file path, it’s difficult to tell cut where to stop.

By using rev, you can flip the string so the extension is at the very beginning (the left side), use cut to grab it, and then use rev again to flip it back to normal.

Let’s extract the extension from /var/log/apache2/access.log.tar.gz:

echo "/var/log/apache2/access.log.tar.gz" | rev | cut -d'.' -f1 | rev

Here is what happens step-by-step:

  1. rev flips the string to: zg.rat.gol.ssecca/2ehcapa/gol/rav/
  2. cut -d'.' -f1 splits the string at the first period (which is now on the left) and grabs the first field: zg
  3. The second rev flips the result back to normal: gz

This pipeline guarantees you will always grab the final file extension, regardless of how many directories or periods are in the original path.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.