简体   繁体   English

在多行中搜索和替换模式

[英]Search and replace patterns on multiple line

I have a pattern like 我有一个像

Fixed pattern
text which can change(world)

I want to replace this with 我想用替换

Fixed pattern
text which can change(hello world)

What I am trying to use 我正在尝试使用的

cat myfile | sed -e "s#\(Fixed Pattern$A_Z_a_z*\(\)#\1 hello#g > newfile

UPDATE: The above word world is also a variable and will change Basically add hello after the first parenthesis encountered after the expression. 更新:上面的单词世界也是一个变量,将发生变化基本上在表达式后的第一个括号之后添加问候。

Thanks in advance. 提前致谢。

Assuming your goal is to add 'hello ' inside of every opening parentheses on the line after 'Fixed pattern' , here is a solution that should work: 假设您的目标是在'Fixed pattern'之后的行中每个圆括号内添加'hello ' ,那么以下解决方案应该可以使用:

sed -e '/^Fixed pattern$/!b' -e 'n' -e 's/(/(hello /' myfile

Here is an explanation of each portion: 这是每个部分的说明:

/^Fixed pattern$/!b    # skip all of the following commands if 'Fixed pattern'
                       #   doesn't match
n                      # if 'Fixed pattern' did match, read the next line
s/(/(hello /           # replace '(' with '(hello '

To do this with sed, use n : 为此,请使用n

sed '/Fixed pattern/{n; s/world/hello world/}' myfile

You may need to be more careful, but this should work for most situations. 您可能需要更加小心,但这在大多数情况下都应该起作用。 Whenever sed sees the Fixed pattern (you may want to use line anchors ^ and $ ), it will read the next line and then apply the substitution to it. 只要sed看到Fixed pattern (您可能要使用行锚^$ ),它将读取下一行,然后对其应用替换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM