Shell script reverse lines of a file

by Vivek Gite [Last updated: October 16, 2007]

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
Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our daily email newsletter to make sure you don't miss a single tip/tricks. Subscribe to our weekly newsletter here!

{ 5 comments… read them below or add one }

1 soraver 05.06.08 at 12:32 pm

and with tac (catin reverse) you can process a file from the end (reverse lines order)

i did A LOT of googling to find this out (a)

2 xpmatteo 07.22.08 at 9:46 am

rev actually reverses characters, *not* lines. If you really want to reverse the *lines* of a file, you can use this:
cat -n myfile | sort -nr | cut -c 9-

3 Scrix1 08.01.08 at 10:45 am

try:-

cat myfile | perl -e “print reverse “

4 The Felis leo 08.12.08 at 12:44 pm

tail -r myfile

-r Reverse. Copies lines from the specified starting point in the file in reverse order. The default for ‘r’ is to print the entire file in reverse order.

5 erik 11.26.08 at 12:32 pm

alas, in Linux Debian…

root@MyServer:/root# tail -r /etc/passwd
tail: invalid option — r
Try `tail –help’ for more information.

On AIX, I did find a version of tail that supports the -r option. Unfortunately, tail -r limits the output to only the last 20480 bytes of a file. If a file is larger, the output of tail is truncated. According to the man page of tail (man tail): “If the file is larger than 20,480 bytes, the -r flag displays only the last 20,480 bytes.”

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Tagged as: , , , , ,

Previous post: Configure Postfix for DNS Blackhole Lists such as dsbl.org / spamhaus.org database

Next post: FreeBSD: Get / Read Hard Disk Temperature using smartd tools