Sed - 从文件中删除第一次出现的字符串 [英] Sed - remove first occurence of string from file

查看:67
本文介绍了Sed - 从文件中删除第一次出现的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 test.txt 的文件,其中包含以下内容:

I have a file called test.txt which contains the following:

test1
test2
test3
test4
test5
test3

我正在使用以下代码从文件中删除 "test3":

I am using the following code to remove "test3" from the file:

sed -i '/test3/d' test.txt

但是我只想删除第一次出现的 "test3"

However I only want to remove only the first occurrence of "test3"

推荐答案

这个 sed one-liner 将帮助您:

This sed one-liner will help you:

sed '0,/test3/{/test3/d}' file
test1
test2
test4
test5
test3

这个 sed 命令使用了 sed 的地址.sed 有不同的地址表达式,这在 sed 的信息页面中有详细解释.

This sed command has used sed's address. Sed has different address expressions, this was explained in detail in sed's Info page.

对于这个命令,0,/pattern/ 会从第一行聚焦到第一行匹配/pattern/,然后执行操作:/pattern/d,即去掉第一个匹配的行.完成此操作后,以下所有行都不会满足地址 0,/pattern/,因此采取了默认操作:按原样打印.

For this command, 0, /pattern/ will focus from the first line till the first line matching /pattern/, then do the action: /pattern/d, that is, remove the first matching line. After this was done, all following lines will not be satisfied with address 0,/pattern/, thus default action was taken: print as they are.

这篇关于Sed - 从文件中删除第一次出现的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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