Nityanand's Weblog

  • view my stats

    free page hit counter
  • Earn Money by viewing ads

  • Useful Links

How to print a file in reversed order in UNIX

Posted by Nityanand Dubey on August 23, 2010

 

Requirement : Print a file in such a manner that the last line should come at the first like a LIFO

Lets create one example of a file (MyFile) containing following three lines

A
B
C

To print a file in a shell we use the cat command

%cat MyFile
this will print all the contents in a file sequentially.

Output :
A
B
C

%cat –n MyFile
This will print the content with the line numbers

Output :
1 A
2 B
3 C

%cat -n MyFile | sort –nr
This will print the lines into reverse order

Output :

3 C
2 B
1 A

%cat -n MyFile | sort –nr | cut –c 8-

Output :
C
B
A

This will cut the initial 8 characters from each line and prints the desired output.

Advertisements

One Response to “How to print a file in reversed order in UNIX”

  1. Have you heard of `tac`?

    $ tac MyFile
    C
    B
    A

    $ tac –version
    tac (GNU coreutils) 5.97
    Copyright (C) 2006 Free Software Foundation, Inc.
    This is free software. You may redistribute copies of it under the terms of
    the GNU General Public License .
    There is NO WARRANTY, to the extent permitted by law.

    Written by Jay Lepreau and David MacKenzie.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s