How to insert text after a certain string in a file?

Right now I’m using

echo "Hello World" >> file.txt

to append some text to a file but I also need to add text below a certain string let’s say [option], is it possible with sed?

EG:

Input file

Some text
Random
[option]
Some stuff

Output file

Some text
Random
[option]
*inserted text*
Some stuff

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Append line after match

  • sed '/[option]/a Hello World' input

Insert line before match

  • sed '/[option]/i Hello World' input

Additionally you can take backup and edit input file in-place using -i.bkp option to sed

Method 2

Yes, it is possible with sed:

sed '/pattern/a some text here' filename

An example:

$ cat test
foo
bar
option
baz
$ sed '/option/a insert text here' test
foo
bar
option
insert text here
baz
$

Method 3

With awk:

awk '1;/PATTERN/{ print "add one line"; print "\and one more"}' infile

Keep in mind that some characters can not be included literally so one has to use escape sequences (they begin with a backslash) e.g. to print a literal backslash one has to write \.

It’s actually the same with sed but in addition each embedded newline in the text has to be preceded by a backslash:

sed '/PATTERN/a
add one line
\and one more' infile

For more details on escape sequences consult the manual.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x