1

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

2 Answers 2

2
$ 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"
Sign up to request clarification or add additional context in comments.

3 Comments

I'm trying to modify the text file not just print
what if replacement text is a variable?
@user2827214 Assuming the replacement text is in a shell variable, see updated answer. If not, let me know the source of the replacement text.
0

This might work for you (GNU sed):

sed '/B/,/C/c\replacement' file

or:

var=replacement; sed '/B/,/C/c\'$var file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.