开发者

regex submatch replace

开发者 https://www.devze.com 2023-03-25 13:35 出处:网络
I\'m trying to replace all occurrences of a word but only when is placed inside a pair of delimiters. Example:

I'm trying to replace all occurrences of a word but only when is placed inside a pair of delimiters. Example:

Original: asdf oldfoo asdf ("asdf oldfoo asdf oldfoo asdf") asdf oldfoo asdf
Desired:  asdf o开发者_StackOverflow中文版ldfoo asdf ("asdf newfoo asdf newfoo asdf") asdf oldfoo asdf

Is there any way to do it with sed or awk?

Thanks!


If the delimiters are '("'and '")' and only one occurrence of the delimiters occurs per line:

sed -e ':begin;s/\(.*(".*\)oldfoo\(.*").*\)/\1newfoo\2/;t begin'

It does not work if you have multiple occurrences per line as the 'oldfoo' in the middle bellow happen to be inside the outer delimiters:

asdf oldfoo asdf ("asdf oldfoo asdf oldfoo asdf") asdf oldfoo asdf ("asdf oldfoo asdf oldfoo asdf") asdf oldfoo asdf

If your delimiters are '('and ')' , this works even if you have multiple delimiters per line:

sed -e ':begin;s/\(.*([^)]*\)oldfoo\([^(]*).*\)/\1newfoo\2/;t begin'


yes, as @nobody mentioned, it's something like

oldfoo(?=[^"]*"([^"]*"[^"]*")*[^"]*$)

i guess you'll probably have to play with escaping of " a bit to make it work correctly with awk/sed

if you have perl it would be

perl -pe 's/oldfoo(?=[^"]*"([^"]*"[^"]*")*[^"]*$)/newfoo/g' whatever.txt

EDIT: ok sorry, i didn't know that sed/awk don't support lookahead/lookbehind at all. I'm afraid that there is no way to do this task without at least lookahead.

0

精彩评论

暂无评论...
验证码 换一张
取 消