小编典典

如何使用sed仅删除文件中第一个出现的行

linux

我有以下文件

titi
tata
toto
tata

如果我执行

sed -i "/tat/d" file.txt

它将删除所有包含的行tat。该命令返回:

titi
toto

但我只想删除包含的文件中出现的第一行tat

titi
toto
tata

我怎样才能做到这一点?


阅读 316

收藏
2020-06-07

共1个答案

小编典典

您可以使用两个地址的形式:

sed '0,/tat/{/tat/d;}' inputfile

这将删除该模式的第一次出现。

引用自info sed

 A line number of `0' can be used in an address specification like
 `0,/REGEXP/' so that `sed' will try to match REGEXP in the first
 input line too.  In other words, `0,/REGEXP/' is similar to
 `1,/REGEXP/', except that if ADDR2 matches the very first line of
 input the `0,/REGEXP/' form will consider it to end the range,
 whereas the `1,/REGEXP/' form will match the beginning of its
 range and hence make the range span up to the _second_ occurrence
 of the regular expression.
2020-06-07