Reputation: 1191
I have a txt file with:
A
B
<anything>
C
D
I want to replace from B to C in the file with a string, but this is not matching:
sed -i -e "s/B.*C/replace/g" $fileName
I have found how to target the multi-line string with:
awk '/B/,/C/' $fileName
Upvotes: 1
Views: 2399
Reputation: 58578
This might work for you (GNU sed):
sed '/B/,/C/c\replacement' file
or:
var=replacement; sed '/B/,/C/c\'$var file
Upvotes: 0
Reputation: 113994
$ awk '/B/{print "Replacement Text"} /B/,/C/{next} 1' "$fileName"
A
Replacement Text
D
Explanation of awk
code:
/B/{print "Replacement Text"}
When we see the B
line, print out the new text, whatever it is.
/B/,/C/{next}
Any any line between B
and C
inclusive, skip the rest of the commands and jump to the next line.
1
This is awk
shorthand for print the current line.
If the replacement text is in the shell variable newtext
, then use:
awk -v new="$newtext" '/B/{print new} /B/,/C/{next} 1'
If you have GNU awk
v4.1.0 or better:
$ awk -i inplace '/B/{print "Replacement Text"} /B/,/C/{next} 1' "$fileName"
With earlier versions:
awk '/B/{print "Replacement Text"} /B/,/C/{next} 1' "$filename" >tmp && mv tmp "$filename"
Upvotes: 2