tags:

views:

64

answers:

4

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]
+2  A: 

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.

Jonathan Leffler
+4  A: 

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
Matthew Slattery
Remarkably similar to what I wrote; maybe at least one of us is correct!
Jonathan Leffler
A: 

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
ghostdog74
A: 

Using ed(1):

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

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