user2827214
user2827214

Reputation: 1191

Replace multiple lines of file in Shell with variable

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

Answers (2)

potong
potong

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

John1024
John1024

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.

Variable text

If the replacement text is in the shell variable newtext, then use:

awk -v new="$newtext" '/B/{print new} /B/,/C/{next} 1'

To modify the file in place

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

Related Questions