Shell script reverse lines of a file

Q. How do I reverse lines of a file under Linux / UNIX bash shell?

A. You need to use the rev utility or command. It copies the specified files to the standard output, reversing the order of characters in every line. If no files are specified, the standard input is read.

Display one line

tail -1 /etc/passwd
Output:

dnsmasq:x:111:65534:dnsmasq,,,:/var/lib/misc:/bin/false

Reverse one line

$ tail -1 /etc/passwd | rev
Output:

eslaf/nib/:csim/bil/rav/:,,,qsamsnd:43556:111:x:qsamsnd

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.