How can I reverse the order of lines in a file? How can I reverse the order of lines in a file? unix unix

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


BSD tail:

tail -r myfile.txt

Reference: FreeBSD, NetBSD, OpenBSD and OS X manual pages.


There's the well-known sed tricks:

# reverse order of lines (emulates "tac")# bug/feature in HHsed v1.5 causes blank lines to be deletedsed '1!G;h;$!d'               # method 1sed -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...