How To Use rev In Your Bash Fu

A common problem when you’re writing bash scripts or creating one liners is to get something from the end of some text. That could be last N characters, the last word etc etc.

There are a number of ways to do this like without using rev but you will need to remember the unique method for each problem. For example, take the following line:

one.two.three.four.five

Say you want to extract the five from the end of the line. The problem is that you need to grab the last word from lines that have different number of different words. This can get complicated.

Unless you use rev.

rev reverses any input e.g.:

$ echo "one.two.three.four.five" | rev
evif.ruof.eerht.owt.eno

Now you can just cut the first word:

$ echo "one.two.three.four.five" | rev | cut -d"." -f1
evif

And finally pass it back through rev:

echo "one.two.three.four.five" | rev | cut -d"." -f1 | rev
five

This will work no matter length of the line or last word e.g.:

$ echo "To be or not to be" | rev | cut -d" " -f1 | rev
be

Or

$ echo "1.2.3.4" | rev | cut -d"." -f1 | rev
4

You will find the technique surprisingly useful now you are aware of it.