Ek1234
Ek1234

Reputation: 429

Sed command : replacing a section in text file (bash)

I want to replace section1 in Input file with section1 in temporary file

My inputfile contains

section1
a1
section2
a2
section3
a1

Here are the contenst of temporaryfile:

section1
a1,b2

My current attempt looks like this:

 sed -i "/$section/,//{/$section/{p;r $temporaryfile};//p;d}"  $Inputfile

I would like to see the following output:

section1
a1,b2
section2
a2
section3
a1

However, my code simply gives me an error message:

sed: -e expression #1, char 0: unmatched `{'
sed: -e expression #1, char 0: unmatched `{'

Referred https://superuser.com/questions/440013/how-to-replace-part-of-a-text-file-between-markers-with-another-text-file

Upvotes: 0

Views: 460

Answers (2)

tripleee
tripleee

Reputation: 189417

Many sed dialects require the braces to be individual "commands". So you need a semicolon before the final closing brace.

Also, the argument after r doesn't have any quoting, so you need to explicitly terminate it e.g. with a newline.

Finally, as a minor optimization, the no-op empty regex // doesn't serve any purpose; you can just leave it out.

sed "/$section/,//{/$section/{p;r $temporaryfile
};p;d;}"

Some shell beginners are flabbergasted that you can have a newline inside the quotes but this is in fact perfectly normal.

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203645

sed is for s/old/new, that is all. For anything else just use awk for simplicity, robustness, portability, efficiency, etc...:

$ cat tst.awk
NR%2 { name = $0; next }
NR==FNR { val[name] = $0; next }
{ print name ORS (name in val? val[name] : $0) }

$ awk -f tst.awk temporaryfile Inputfile
section1
a1,b2
section2
a2
section3
a1

Upvotes: 1

Related Questions