how to append new text to specific text in a file, using BASH?
What is the best solution to append开发者_StackOverflow社区ing 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]
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
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.
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
Using ed(1):
lines='test1=data
test2=data
test3=data'
printf '%s\n' H '/\[setting2\]/a' "$lines" . wq | ed -s testfile.txt
精彩评论