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:


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

Now you can just cut the first word:

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

And finally pass it back through rev:

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

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


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

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