linkyndy
linkyndy

Reputation: 17900

Add lines of text to specific line in a variable

I have the following file, CHANGELOG.rst:

some text
=========

header
------

* list
* list

header
------

* list

I need to add an entry to this file, right after the file's title, so that the updated file will look as the following:

some text
=========

new header
----------

* new list

header
------

* list
* list

header
------

* list

I add that the

new header
----------

* new list

part is already present in a $CHANGES variable.

I know this can be done with sed but I have no idea how to tackle it.

Upvotes: 0

Views: 1335

Answers (6)

linkyndy
linkyndy

Reputation: 17900

I was able to find a solution to my problem in this stackoverflow answer.

Thanks to @mklement0, the code is:

sed -i "4 i\
${CHANGES//$'\n'/\\$'\n'}" ./CHANGELOG.rst

Upvotes: 0

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed '/^header/ i\
your content like New Header\
and his content
' YourFile

but this occur at every header

specificaly (as requested)

sed '/^header/ i\
new header\
----------\
\
* new list\

' YourFile

Upvotes: 0

Timmah
Timmah

Reputation: 2121

Use below if you want to ensure you do this for the first occurrence only:

CHANGES="line1\nline2"
sed -i "0,/\(^=\+$\)/s//\1\n${CHANGES}/" filename

Upvotes: 1

Amit
Amit

Reputation: 20456

With sed:

sed -i '/PATTERN/a  Line which you want to append' filename

-i is for in-place subsitution

For your example:

sed -i "/=========/a ${CHANGES}" file

some text
=========

new header
----------

* new list

header
------

* list
* list

header
------

* list

Upvotes: 3

kojiro
kojiro

Reputation: 77059

I wouldn't use sed to inject a value into a text file. I'd use ed.

ed file <<EOF
4i
$yourtext
.
w
EOF

This says,

  1. "start inserting at the fourth line"
  2. insert "$yourtext"
  3. stop inserting
  4. write.

Upvotes: 1

philshem
philshem

Reputation: 25331

Here is my ugly solution using grep:

grep -B100000 "=========" CHANGELOG.rst > new.txt
echo >> new.txt
echo "new header" >> new.txt
echo "----------" >> new.txt
echo >> new.txt
echo "\* new list" >> new.txt
echo >> new.txt
grep -A100000 "=========" CHANGELOG.rst >> new.txt

grep -A gets the lines after the matching string, and grep -B gets the lines after. It only works if the matching string where you want to split the file exists only once.

Upvotes: 0

Related Questions