How can I reverse the order of lines in a file?
I'd like to reverse the order of 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?
BSD tail:
tail -r myfile.txt
Reference: FreeBSD, NetBSD, OpenBSD and OS X manual pages.
Also worth mentioning: tac
(the, ahem, reverse of cat
). Part of coreutils.
Flipping one file into another
tac a.txt > b.txt
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...
链接地址: http://www.djcxy.com/p/77062.html上一篇: 使用sed从文本文件中删除特定的行号?
下一篇: 我怎样才能扭转文件中的行的顺序?