Shell script reverse lines of a file

Posted on in Categories , , , , , , , 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


Reverse one line

$ tail -1 /etc/passwd | rev


Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

18 comment

  1. 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.

      1. Seems Erik got to the source of it: it’s not supported in debian. I’m running Ubuntu; it’s not supported in here either.

        tac is the best answer though: does exactly what we all want and is the simplest

  2. alas, in Linux Debian…

    [email protected]:/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.”

  3. Works better:

    cat -n temp| sort -nr|awk '{$1="";print}'

    Tested on HPUX. tac and cat -r are not options on UNIX, probably they are part of GNU variants. The perl one-liner didn't work, but it should be easy to make one...

  4. I used rev in:
    find directory -type f | rev | sort | rev | xargs tar -Af archive.tar
    it gave me 122MB after gzipping instead of 128MB produced by
    tar -czf archive.tgz directory
    Poor man’s solid compression :).

  5. [[email protected] ~/perl]$ awk ‘BEGIN{FS=OFS=”.”}{print $7.$6$5,$4,$3,$2,$1}’ /etc/passwd | tail -1

    If you run this command it will reverse the columns.

Leave a Comment