如何使用sed仅删除文件中第一个出现的行 [英] How to remove only the first occurrence of a line in a file using sed
本文介绍了如何使用sed仅删除文件中第一个出现的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下文件
titi
tata
toto
tata
如果我执行
sed -i "/tat/d" file.txt
它将删除所有包含tat
的行.该命令返回:
It will remove all the lines containing tat
. The command returns:
titi
toto
但是我只想删除包含tat
的文件中出现的第一行:
but I want to remove only the first line that occurs in the file containing tat
:
titi
toto
tata
我该怎么办?
推荐答案
您可以使用两个地址的形式:
You could make use of two-address form:
sed '0,/tat/{/tat/d;}' inputfile
这将删除模式的首次出现.
This would delete the first occurrence of the pattern.
从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.
这篇关于如何使用sed仅删除文件中第一个出现的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文