使用sed替换除注释以外的第一次发生(Replacing first occurence except comments using sed)

编程入门 行业动态 更新时间:2024-10-13 20:17:50
使用sed替换除注释以外的第一次发生(Replacing first occurence except comments using sed)

我有一个形式的文本文件:

a = 1 #b = [2,3] c = 4 d = [5,6] e = [7,8]

我想用一个数字替换括号(和括号)内的模式,但忽略注释中的匹配,最好使用sed。

对于只有一个匹配行的文件,我已经使用过

sed -i "/^#/!s/\[.*\]/9/" myfile

如果还有更多,如何修改它以仅替换第一场比赛?

I have a text file of the form:

a = 1 #b = [2,3] c = 4 d = [5,6] e = [7,8]

I want to replace the pattern inside the brackets (and the brackets) with a number, but ignore matches in the comments, preferably using sed.

For files with exactly one matching line, I've used

sed -i "/^#/!s/\[.*\]/9/" myfile

How can this be modified to replace only the first match if there are more?

最满意答案

这是正确的,因为只是改变了第一次发生。

awk '!end && /^[^#]+ = \[/ {$3="9"; end=1}1' myfile

如果没有结束标志,并且行不是从#开始并匹配到= [ ,则更改第三列并设置标志以防止在下次出现时更改。

a = 1

#b = [2,3]

c = 4

d = 9

e = [7,8] <---这不会随意改变

This is the correct, because changing just the first occurence.

awk '!end && /^[^#]+ = \[/ {$3="9"; end=1}1' myfile

if there is not end flag and line is not beggining from # and match to = [, then change the third column and set the flag to prevent changing in next occurences.

a = 1

#b = [2,3]

c = 4

d = 9

e = [7,8] <--- this is not changed as you want

更多推荐

本文发布于:2023-08-04 20:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1422655.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:注释   发生   sed   comments   occurence

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!