Quickly Reverse File Contents With This Linux Command

Most people who use Linux operate in a graphical user interface (GUI), which provides easy-to-use menus and icons for common tasks. However, many power users prefer to work in the Linux command line, as it provides a more powerful and efficient way to interface with the operating system. Here is a cheat sheet that covers the most commonly used Linux commands.

This article demonstrates the use of a lesser-known Linux command called rev. It is a part of util-linux package which is a basic package and comes installed with most distros.

Rev is a powerful and easy-to-use command which can reverse characters and output the reversed form. The rev command does this by reading the lines character-wise and reversing them in the order that they are read.

Using rev as a standalone command:

Rev in its basic form accepts lines of characters and then reverses. To do this, open the Terminal and type in:

 rev

Rev command in Linux

All it will do is reverse whatever you enter. Exit using Ctrl-C.

Using rev to process text files:

The power of the rev command though as with other commands in Linux is when you combine it with other inputs. 

So you can also directly enter characters through the echo command and get the reverse output.

Echo and rev command used together

Besides these, you can also input files and use the rev command to reverse their contents.

Here is how:

The sample file is named hello.txt

Contents of a sample text file
A sample text file to be reversed

To display its contents in reverse, the command will be:

 cat hello.txt | rev

Pipe the contents of text file with rev to reverse the contents
Contents of text file reversed

This command pipes the output of hello.txt to rev, which then reverses the lines of characters based on the order they are seen. 

Pretty cool.

Let’s take another file named numbers.txt. The command to reverse its contents will be:

 cat numbers.txt | rev

Rev processes characters line-wise

Notice how the initial rows of single numbers remain unchanged even after rev processes this file. This is because each of these lines only has one character (one number on each line), so there is nothing to reverse. 

The number sequence at the end though is reversed and rev shows the output. 

The man page for rev:

As with other Linux commands, you can read the man page for rev:

 man rev

The man page for rev
The man page for rev command

Also, there is the -h parameter that displays the help contents for using rev.

 rev -h

It is a basic command that does not need a lot of parameters.

The help parameters in rev command
The help parameters in rev command

Overall, rev is a versatile command that can be used for advanced text processing by combining it with other commands. By the way, there is also another lesser-known command named look to search for lines from the Terminal.

All done.

Leave a Comment