I'd like to reverse the lines in a text file (or stdin), preserving the contents of each line.
So, ie, starting with:
foo
bar
baz
I'd like to end up with
baz
bar
foo
Is there a standard unix commandline utility for this?
I'd like to reverse the lines in a text file (or stdin), preserving the contents of each line.
So, ie, starting with:
foo
bar
baz
I'd like to end up with
baz
bar
foo
Is there a standard unix commandline utility for this?
Also worth mentioning: tac
(the, ahem, reverse of cat
). Part of coreutils.
There's the well-known sed tricks:
# reverse order of lines (emulates "tac")
# bug/feature in HHsed v1.5 causes blank lines to be deleted
sed '1!G;h;$!d' # method 1
sed -n '1!G;h;$p' # method 2
(Explanation: prepend non-initial line to hold buffer, swap line and hold buffer, print out line at end)
If you can't remember that,
perl -e 'print reverse <>'
On a system with GNU utilities, the other answers are simpler, but not all the world is GNU/Linux...
You can do it using a combination of tail and head :)
file=$1
lineCount=`cat $file | wc -l`
counter=0
while [ $counter -le $lineCount ]
do
tail -$counter $file | head -1
counter=`expr $counter + 1`
done