从 Bash 中的文件中删除最后一行 [英] Remove the last line from a file in Bash
本文介绍了从 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屋!
查看全文