如果之前没有另一个模式,则替换第一次出现的模式 [英] Replace first occurrence of a pattern if not preceded with another pattern

查看:43
本文介绍了如果之前没有另一个模式,则替换第一次出现的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 GNU sed,我尝试替换文件中第一次出现的模式,但如果在匹配之前有另一个模式,我不想替换.

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.

例如,如果文件包含带有bird [number]"的行,如果此模式之前没有cat"字样,我想用0"替换该数字.

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.

示例文本

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

预期结果:

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

我尝试结合 如何使用 sed 仅替换文件中的第一次出现?Sed 正则表达式和子字符串否定 解决方案并想出了类似

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]+/ 应该匹配第一次出现的 (Bird +)[0-9]+ 如果 cat.*bird +[0-9]+ 模式不匹配,但我得到

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.

推荐答案

这可能对你有用(GNU sed):

This might work for you (GNU sed):

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

如果一行在单词 bird 之前包含单词 cat,则结束该行的处理.尝试将单词 bird 后面的数字替换为零.如果不成功,则结束该行的处理.否则读取/打印所有以下行,直到文件末尾.

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.

也可以写成:

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

这篇关于如果之前没有另一个模式,则替换第一次出现的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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