3

In bash, how can I find and replace some text containing a new line?

I want to match exactly 2 lines as specified (I can't match them separately as both lines appear at different places separately & I only want to replace where both lines appear consecutively). Using sed I was able to find and replace the individual lines and new line separately, but not together!

In case if needed, below are the lines I want to find and replace (from multiple files at once!):

} elseif ($this->aauth->is_member('Default')) { $form_data['userstat'] = $this->aauth->get_user()->id;

4
  • and you want to replace with? Commented Oct 9, 2017 at 21:21
  • sorry, but does it actually matter? Commented Oct 9, 2017 at 21:24
  • if you are replacing using captured groups, yes; so, good luck Commented Oct 9, 2017 at 21:32
  • I don't know what does that mean. But what I actually need is to remove the second line wherever those both lines occur together. Despite of this specific case I'd like to know how to find and replace multiple lines in general. Thanks. Commented Oct 9, 2017 at 21:37

2 Answers 2

3

In general you can used sed -z which tells sed to use the null-character to split lines. Assume you have the file text containing

Hello World This is a line line1 line2 Hello World, again line1 line2 end 

Executing sed -z -e 's/line1\nline2/xxx/g' text yields

Hello World This is a line xxx Hello World, again xxx end 

You can add * (that is <space><star>) to handle inconsistent white spaces.


In your specific case if you want to delete the second line you can use a block statement to advance to the next line and delete it if it matches the second line

sed -e '/line1/{n;/line2/d}' text 
Sign up to request clarification or add additional context in comments.

Comments

1

This might work for you (GNU sed):

sed -i 'N;s/first line\nsecond line/replacement/;P;D' file ... 

Keep a moving window of two lines in the pattern space and replace when necessary.

N.B. -i option updates file(s) in place.

Also using a range and the change command:

sed -i '/first line/,/second line/c\replacement1\nreplacement2\netc' file ... 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.