How can I reverse the order of lines in a file?
Also worth mentioning: tac
(the, ahem, reverse of cat
). Part of coreutils.
Flipping one file into another
tac a.txt > b.txt
at the end of your command put:
| tac
tac does exactly what you're asking for, it "Write each FILE to standard output, last line first."
tac is the opposite of cat :-).
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)
Alternatively (with faster execution) from the awk one-liners:
awk '{a[i++]=$0} END {for (j=i-1; j>=0;) print a[j--] }' file*
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...
BSD tail:
tail -r myfile.txt
Reference: FreeBSD, NetBSD, OpenBSD and OS X manual pages.