Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SED: Append a line at the end of a range

Tags:

bash

sed

I'm looking to add some lines before the end of a range in a file.

sed '/BEGIN/,/END/ /$/i \ SOME TEXT TO ADD' /path/to/foo

  • Original file: random text BEGIN foo bar END random text
  • Expected behavior after SED: random text BEGIN foo bar SOME TEXT TO ADD END random text

Any ideas on how to accomplish this?

like image 859
clvx Avatar asked Jan 24 '26 05:01

clvx


2 Answers

This might work for you (GNU sed):

sed '/BEGIN/,/END/!b;/END/iSOME TEXT TO ADD' file

If there are lines not between BEGIN and END print as normal otherwise if the line contains END insert some text.

like image 106
potong Avatar answered Jan 26 '26 23:01

potong


Why don't you just look for the end tag, and insert before:

sed '/END/ iSOME TEXT TO ADD' /path/to/foo

Otherwise you must use several lines:

sed '/BEGIN/,/END/ {
    /END/ iSOME TEXT TO ADD
    }' /path/to/foo
like image 22
chw21 Avatar answered Jan 27 '26 00:01

chw21



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!