James Nine
James Nine

Reputation: 2618

how to append new text to specific text in a file, using BASH?

What is the best solution to appending new text after an existing block of text in a text file, using a BASH script?

for example, I have a config file with the following:

[setting1]

...

[setting2]

...

[setting3]

I want to add some text after [setting2], e.g.:

test1=data
test2=data
test3=data

Therefore, I want it to look like this after the script is run:

[setting1]

...

[setting2]
test1=data
test2=data
test3=data
...

[setting3]

Upvotes: 1

Views: 856

Answers (4)

yabt
yabt

Reputation: 1

Using ed(1):

lines='test1=data
test2=data
test3=data'

printf '%s\n' H '/\[setting2\]/a' "$lines" . wq | ed -s testfile.txt

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342263

you can do it with just the shell. The basic idea is to search for the pattern and when found, print out the current line and your 3 new lines

exec 4<"file"
while read -r line
do
   case "$line" in
    *setting2*)
      echo "$line"
      printf "test1=data\ntest2=data\ntest3=data\n"
   esac
done >t
exec 4<&-
mv t file

Also, using awk

awk '/setting2/{$0=$0"\ntest1=data\ntest2=data\ntest3=data"}1' file

Upvotes: 0

Matthew Slattery
Matthew Slattery

Reputation: 46998

You could do this with sed:

$ sed -e '/^\[setting2\]$/a\
test1=data\
test2=data\
test3=data' yourfile > yourfile.new

(note new lines immediately after the \ characters).

...or with the -i flag to modify the file in-place:

$ sed -i -e '/^\[setting2\]$/a\
test1=data\
test2=data\
test3=data' yourfile

Upvotes: 4

Jonathan Leffler
Jonathan Leffler

Reputation: 753475

One way is:

sed -e '/^\[setting2]/a\
test1=data\
test2=data\
test3=data' $file > new.$file
mv new.$file $file

With GNU sed, there is the '-i' option to do an 'in-place' edit - which saves having to write to a new file and move the new file over the old one.

Upvotes: 2

Related Questions