从Bash中的文件中删除最后一行 [英] Remove the last line from a file in Bash

查看:95
本文介绍了从Bash中的文件中删除最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a file, foo.txt, containing the following lines:

a
b
c

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

I want a simple command that results in the contents of foo.txt being:

a
b

推荐答案

使用 GNU sed :

sed -i '$ d' foo.txt

-i选项在低于3.95的GNU sed版本中不存在,因此您必须将其用作带有临时文件的过滤器:

The -i option does not exist in GNU sed versions older than 3.95, so you have to use it as a filter with a temporary file:

cp foo.txt foo.txt.tmp
sed '$ d' foo.txt.tmp > foo.txt
rm -f foo.txt.tmp

当然,在这种情况下,您也可以使用head -n -1代替sed.

Of course, in that case you could also use head -n -1 instead of sed.

MacOS:

在Mac OS X(自10.7.4版)上,与上述sed -i命令等效.

On Mac OS X (as of 10.7.4), the equivalent of the sed -i command above is

sed -i '' -e '$ d' foo.txt

这篇关于从Bash中的文件中删除最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆