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

2019-01-03 00:37发布

I'd like to reverse the order of lines in a text file (or stdin), preserving the contents of each line.

So, i.e., starting with:

foo
bar
baz

I'd like to end up with

baz
bar
foo

Is there a standard UNIX commandline utility for this?

20条回答
Root(大扎)
2楼-- · 2019-01-03 01:02

Also worth mentioning: tac (the, ahem, reverse of cat). Part of coreutils.

Flipping one file into another

tac a.txt > b.txt
查看更多
够拽才男人
3楼-- · 2019-01-03 01:03

I had the same question, but I also wanted the first line (header) to stay on top. So I needed to use the power of awk

cat dax-weekly.csv | awk '1 { last = NR; line[last] = $0; } END { print line[1]; for (i = last; i > 1; i--) { print line[i]; } }'

PS also works in cygwin or gitbash

查看更多
Ridiculous、
4楼-- · 2019-01-03 01:06

Best solution:

tail -n20 file.txt | tac
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-03 01:06
sort -r < filename

or

rev < filename
查看更多
时光不老,我们不散
6楼-- · 2019-01-03 01:08

Try the following command:

grep -n "" myfile.txt | sort -r -n | gawk -F : "{ print $2 }"
查看更多
Lonely孤独者°
7楼-- · 2019-01-03 01:11

The simplest method is using the tac command. tac is cat's inverse. Example:

$ cat order.txt
roger shah 
armin van buuren
fpga vhdl arduino c++ java gridgain
$ tac order.txt > inverted_file.txt
$ cat inverted_file.txt
fpga vhdl arduino c++ java gridgain
armin van buuren
roger shah 
查看更多
登录 后发表回答