PravinCG
PravinCG

Reputation: 7708

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.

Upvotes: 0

Views: 136

Answers (2)

Andrew Clark
Andrew Clark

Reputation: 208405

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:

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 '

Upvotes: 3

William Pursell
William Pursell

Reputation: 212198

To do this with sed, use 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.

Upvotes: 2

Related Questions