我有一个文件,foo.txt,包含以下行:

a
b
c

我想要一个简单的命令,导致foo.txt的内容为:

a
b

当前回答

在macOS上,head -n -1不起作用,但你可以使用这个命令:

cat file.txt | tail -r | tail -n +2 | tail -r

Tail -r将其输入中的行顺序颠倒 Tail -n +2输出输入中从第二行开始的所有行

其他回答

这是目前为止最快和最简单的解决方案,特别是对大文件:

head -n -1 foo.txt > temp.txt ; mv temp.txt foo.txt

如果你想删除顶部行,使用这个:

tail -n +2 foo.txt

这意味着输出行从第2行开始。

不要使用sed从文件的顶部或底部删除行——如果文件很大,它会非常非常慢。

红宝石(1.9+)

ruby -ne 'BEGIN{prv=""};print prv ; prv=$_;' file

你也可以试试这个方法:删除最后n行数的例子。

= 0;While [$a -lt 4];do sed -i '$ d' output.txt;A =expr $ A + 1;完成

删除文件(output.txt)的最后4行。

echo -e '$d\nw\nq'| ed foo.txt
awk "NR != `wc -l < text.file`" text.file &> newtext.file

这段代码可以达到目的。