How to Reverse Text Horizontally Using the rev Command in Linux

When processing text files in a Linux terminal, you will often encounter situations where data needs to be flipped for a specific script or parser to read it correctly. While the tac command reverses a file vertically (flipping the order of the lines from bottom to top), the rev (reverse) command works horizontally. It reads a file line by line and perfectly reverses the order of every single character on that line.

How to Use the rev Command

The rev utility is incredibly simple to use because it requires virtually no arguments or flags. You simply pass it the name of a file.

Imagine you have a file named passwords.txt containing three simple lines:

apple
banana
cherry

If you run the command:

rev passwords.txt

The terminal will instantly output:

elppa
ananab
yrrehc

Notice that the vertical order of the lines (apple, then banana, then cherry) remained exactly the same. However, the text on each individual line was flipped backward.

Reversing Interactive Text Input

If you do not specify a file, the rev command will enter an interactive mode, patiently waiting for you to type directly into the terminal.

rev

After pressing enter, the terminal will drop down to a blank line. If you type the phrase Hello World! and press Enter, the utility will immediately spit back !dlroW olleH. It will continue doing this for every line you type until you press Ctrl + D to send an End-Of-File (EOF) signal and close the program.

Practical Uses for the rev Command

While reversing the word “banana” might seem like a parlor trick, rev is extremely powerful when combined with other text-processing tools like cut or awk.

For example, imagine you have a list of hundreds of file paths, and you only want to extract the final filename at the very end of the path (ignoring all the directories leading up to it).

/var/log/apache2/access.log
/home/user/documents/report.pdf

Using standard tools to extract the “last” item is mathematically difficult because the number of directories changes on every line. However, if you pipe the text into rev first, the filename becomes the “first” item on the line, making it incredibly easy to extract before flipping it back to normal.

rev file_paths.txt | cut -d '/' -f 1 | rev

This command pipeline reverses the path, uses cut to grab everything up to the first slash, and then reverses the text back to its original readable format, perfectly extracting access.log and report.pdf.

Get the best tech tips delivered straight to your inbox.

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