Tuesday, August 14, 2007

Reverse the Contents of a File

The tail command can be used to reverse the contents of a file. Here's an example.

# cat > filename
THIS IS AN EASY WAY TO REVERSE THE CONTENT OF A FILE.
THE REVERSAL WILL DO MORE THAN 10 LINES. IT WILL REVERSE THE ENTIRE FILE.
EOM
.
# tail -r filename
.
EOM
THE REVERSAL WILL DO MORE THAN 10 LINES. IT WILL REVERSE THE ENTIRE FILE.
THIS IS AN EASY WAY TO REVERSE THE CONTENT OF A FILE.

By the way, this command line entry will do the same thing as tail -r.
# perl -e 'print reverse <>' filename

5 comments:

Anonymous said...

You can also use 'tac' to perform the same action

Brad said...

tac is more flexible, but it isn't universally available like "tail" is.

Solaris doesn't have tac unless you install the coreutils package.

Elijah said...

I had a need to write one script that worked on both linux and AIX. All of our linux installs have tac which is nice, but AIX did not. In AIX at least, tail -r is limited to 20K. I ended up using the following mash of commands.


cat -n filename|sort -rn|cut -c8-


Ugly but workable.

Ma'ña Bräu Jedi Warrior said...

hey thanks for that :-D the "cat -n" solution in the comments is cool too

Dhimant's Learning said...

Yes, following observations...

1) tac is not universally available. FreeBSD and AIX not supported tac

2) tail should work in any situation.. not sure about Elijah's comment

3) perl solution written in the blog will not work. It will print whole file in reverse order and not print from last line to first line.

4) cat -n will not print lines from last to first.. it will just add the line number against respective line..