Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...