Linux 删除文件的最后一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5177169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:06:03  来源:igfitidea点击:

Deleting last line of a file

linuxshell

提问by Shweta

I want to delete last line of a file on a particular condition. I used sed and cut but they work only on the output stream but I want to do this in the file. Can someone help me? Thanks in advance.

我想在特定条件下删除文件的最后一行。我使用了 sed 和 cut 但它们仅适用于输出流,但我想在文件中执行此操作。有人能帮我吗?提前致谢。

采纳答案by Shad

sed -ie '$d' filename.txt

The ioption tells sedto edit the file in place.

i选项告诉sed在适当的位置编辑文件。

回答by alcoholtech

You can always do:

你总是可以这样做:

cat * > out

Where you could remove 'cat *' with whatever you're doing, and the out is the result of that command.

无论您在做什么,都可以删除“cat *”,而 out 是该命令的结果。

I can take a more thorough look if you provide more information on what you're trying to do.

如果您提供有关您要执行的操作的更多信息,我可以进行更彻底的研究。

回答by darklion

I'll use a variant on another answer and suggest a simple use of ed:

我将在另一个答案上使用一个变体,并建议简单使用 ed:

ed tmp.tmp << EOC
$
d
w
q
EOC

Otherwise you can use sed/cut to a temporary file and mvto overwrite the starting file.

否则,您可以使用 sed/cut 到临时文件并mv覆盖起始文件。