Tuesday, September 18, 2012

Linux print file reversed

Within Linux you have several commands that will read a file and put the output from this file to your screen. Or you can pipe it into an other file if that is what you need. however from time to time you might want to read the file in reversed order. For example if you have an application that is writing information to a file and you have to put this file in reversed order into a input file for another program or to be loaded into a database.

as with most things in Linux there are several ways to dot his. you could read the number of lines by using wc -l and use this number in loop of a bash program to print the file line by line in reversed order.

however, as stated, there are more ways to do this. This most easy way to read a file in reversed order in Linux is making use of the tac command. The tac command will do exactly as described above without any line of coding or any other smart trick. It just reads a file and print the content in reversed order to your screen (or pipe it into another file).

NAME
       tac - concatenate and print files in reverse

SYNOPSIS
       tac [OPTION]... [FILE]...

DESCRIPTION
       Write each FILE to standard output, last line first.  With no FILE, or when FILE is -, read standard input.

       Mandatory arguments to long options are mandatory for short options too.

       -b, --before
              attach the separator before instead of after

       -r, --regex
              interpret the separator as a regular expression

       -s, --separator=STRING
              use STRING as the separator instead of newline

       --help display this help and exit

       --version
              output version information and exit

No comments: