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

a
b
c

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

a
b

当前回答

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

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

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

tail -n +2 foo.txt

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

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

其他回答

Linux

$表示最后一行,d表示删除:

sed '$d' ~/path/to/your/file/name

操作系统

相当于sed -i:

sed -i '' -e '$ d' ~/path/to/your/file/name
awk "NR != `wc -l < text.file`" text.file &> newtext.file

这段代码可以达到目的。

删除zshrc文件中的最后一行,例如:

cat ~/.zshrc
sed -i '' -e '$ d' ~/.zshrc
cat ~/.zshrc

Mac用户

如果只希望删除最后一行输出而不更改文件本身做

Sed -e '$ d' foo.txt

如果要删除输入文件本身的最后一行

Sed -i " -e '$ d' foo.txt

要从文件中删除最后一行而不读取整个文件或重写任何内容,可以使用

tail -n 1 "$file" | wc -c | xargs -I {} truncate "$file" -s -{}

要删除最后一行并将其打印到stdout(“弹出”它),可以将该命令与tee结合使用:

tail -n 1 "$file" | tee >(wc -c | xargs -I {} truncate "$file" -s -{})

这些命令可以有效地处理一个非常大的文件。这与Yossi的答案相似,并受到了启发,但它避免了使用一些额外的函数。

如果你想重复使用这些,并且想要错误处理和一些其他功能,你可以在这里使用poptail命令: https://github.com/donm/evenmoreutils