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
mark?
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
putorius.net
ipaddr.pub
www.putori.us
wikipedia.org
putorius.net
www.wikipedia.org
www.ipaddr.pub
putori.us
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
ipaddr.pub
www.ipaddr.pub
wikipedia.org
www.wikipedia.org
putori.us
www.putori.us
putorius.net
putorius.net
The list is now sorted alphabetically using the last letter in each line.
Conclusion
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.
Helpful Links
Join Our Newsletter
Categories
- Bash Scripting (17)
- Basic Commands (51)
- Featured (7)
- Just for Fun (5)
- Linux Quick Tips (98)
- Linux Tutorials (65)
- Miscellaneous (15)
- Network Tools (6)
- Reviews (2)
- Security (32)