rev Command - Reverse Order of Characters on Command Line
The Linux rev command is useful little utility that reverses lines of text character-wise. It will take the specified file and print it to standard output, reversing the order of the characters on each line.
Here is an example:
$ cat /etc/redhat-release
Fedora release 29 (Twenty Nine)
$ rev /etc/redhat-release
)eniN ytnewT( 92 esaeler arodeF
If no file is specified, it will read standard input until you exit using CTRL+D or otherwise kill the process.
At first it may seem silly, but like all things Linux it is only limited by your imagination. In the following quick tip, we will show you some practical uses for the rev command.
Remove Last Character from String
Using rev and the cut command you can strip the last character from a string.
$ echo 'Remove this question mark?' | rev | cut -c 2- | rev
Remove this question mark
Here we are using rev to reverse the line, then cutting the first character, then reversing it again. The end result is the last character ( ? ) is removed.
Strip Everything Except Last Word in a Line
Similar to the example above, we can strip everything from a line except the last word as defined by spaces.
$ echo 'Remove this question mark?' | rev | cut -d' ' -f1| rev
By using the cut command delimited on spaces, we are able to remove everything except the first word (-f1). Using rev allows us to reverse this and remove the last word.
Sorting File Lines by Last Character
The rev command is often used to reverse lines, apply a sort and then reverse the line back to it's original state. Take the following text file as an example.
$ cat websites.txt
If we wanted to sort by the last character in each line, we can use rev to revere the lines, sort by the last character, then reverse the strings back to their original state.
$ cat websites.txt | rev | sort | rev
The list is now sorted alphabetically using the last letter in each line.
That's rev in a nutshell. The rev command has no options, it serves one purpose. Although it will probably never get used every day, you may find yourself needing it one day, I know I have.
This site uses Akismet to reduce spam. Learn how your comment data is processed.