1

I've been trying to replace successive lines with the following sed commands :

sed -i -e '/string1/{N;s/string2/string2_replaced/;N;s/string3/string3_replaced}' file1

sed -i -e '/string1/{n;s/string2/string2_replaced/;n;s/string3/string3_replaced}' file1

where file1 contains:

string1
string2
string3

I keep getting sed: unmatched '/'. How can I change the contents of file1 to:

string1
string2_replaced
string3_replaced

so that string2 and string3 are replaced only if they are on successive lines and if they are immediately after a line that matches string1?

Also, how can I search and replace string2 if I am not sure where (which line) exactly it occurs, but sure that it occurs after string1?

6
  • 1
    You missed the last /, it's s/string3/string3_replaced/. Also not all sed implementations support multiple commands in the same line within { and }.
    – cuonglm
    Commented May 4, 2016 at 9:08
  • This isn't complicated. You just pull in the next two lines (with N;N) if the line matches string1 and then check if the pattern space matches string1 followed by a newline followed by string2 followed by another newline and string3 (newline is \n). If so, you do the substitutions. You think you can do it by yourself ? Commented May 4, 2016 at 9:34
  • I did that. :) Now, I would like to know a way to replace string2 when I don't know where exactly it comes (say maybe a few lines later) after string1. Commented May 4, 2016 at 9:53
  • Good :) If you managed to do it please post an answer (you'll get upvoted if the answer is correct). I'm not sure I understand your other question: do you want to replace string2 only if it occurs somewhere in the file after string1 (but not before it) ? Commented May 4, 2016 at 9:57
  • That's right. The scenario when I don't know how many lines after string1 string2 occurs. Commented May 4, 2016 at 10:05

1 Answer 1

5

You missed the last /, it's s/string3/string3_replaced/:

sed -e '/string1/{N;s/string2/string2_replaced/;N;s/string3/string3_replaced/}' file1

Note that not all sed implementations support multiple commands in the same line within { and }. For portability:

sed -e '/string1/ {
  N
  s/string2/string2_replaced/
  N
  s/string3/string3_replaced/
}' file1
1
  • it seems something like s/^(.*):.*$/\1: false doesn't work in {N;/s/<STRING>/<STRING>/;} format, am I right?. ie: convert xxx: true to xxx: false by sed -e '/string1/ {n;s/^([^:]+):.*$/\1: false/;}' file.
    – Marslo
    Commented Sep 28, 2020 at 13:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .