Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

sed - Replace first occurrence of a pattern if not preceded with another pattern

Using GNU sed, I try to replace first occurrence of pattern in file, but I don't want to replace if there is another pattern before the match.

For example, if the file contains line with "bird [number]" I want to replace the number with "0" if this pattern has no "cat" word any where before.

Example text

dog cat - fish bird 123
dog fish - bird 1234567
dog - cat fish, lion bird 3456

Expected result:

dog cat - fish bird 123
dog fish - bird 0
dog - cat fish, lion bird 3456

I try to combine How to use sed to replace only the first occurrence in a file? and Sed regex and substring negation solutions and came up with something like

sed -E '0,/cat.*bird +[0-9]+/b;/(bird +)[0-9]+/ s//10/'

where 0,/cat.*bird +[0-9]+/b;/(bird +)[0-9]+/ should match the first occurrence of (bird +)[0-9]+ if the cat.*bird +[0-9]+ pattern does not match, but I get

dog cat - fish bird 123
dog fish - bird 0
dog - cat fish, lion bird 0

The third line is also changed. How can I prevent it? I think it is related to address ranges, but I do not get it how to negate the second part of the address range.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This might work for you (GNU sed):

sed '/<cat>.*<bird>/b;s/<(bird) +[0-9]+/1 0/;T;:a;n;ba' file

If a line contains the word cat before the word bird end processing for that line. Try to substitute the number following the word bird by zero. If not successful end processing for that line. Otherwise read/print all following lines until the end of the file.

Might also be written:

sed -E '/cat.*bird/b;/(bird +)[0-9]+/{s//10/;:a;n;ba}' file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...