Add a block of text after another with sed
I want to add the following block of text // More text here "mysite.com" zone {type master; file "mysite.com.fwd"; allow-update {none; }; };
right after the block of text shown below
zone "." IN {
type hint;
file "named.ca";
};
Ultimately the file will look like this
//There are more lines up here
zone "." IN {
type hint;
file "named.ca";
};
zone "mysite.com" {
type master;
file "mysite.com.fwd";
allow-update { none; };
};
//There are more lines below here
The tricky thing here is what \n
in the pattern to match doesn't work with sed.
Thanks for the help in advanced
source to share
I would do it like this:
sed "/^};/a \ \nzone \"mysite.com\" {\n type master;\n file \"mysite.com.fwd\";\n allow-update { none; };\n};\n" test.conf
Before
zone "." IN {
type hint;
file "named.ca";
};
After
zone "." IN {
type hint;
file "named.ca";
};
zone "mysite.com" {
type master;
file "mysite.com.fwd";
allow-update { none; };
};
^};
- this is a template after which you add a new block with a
, you can change the template if you need it.
Another approach with sed, which is more flexible, is to use a file in which you have a new block:
sed "/^};/r block.conf" test.conf
Here we simply add text from block.conf
to test.conf
using the read command r
. /^};/
again your template.
This range template should be uniqe /file \"named.ca\";/,/^};/
I guess this should work for you pretty much
sed "/file \"named.ca\";/,/^};/ {
/file*/n
a \ \nzone \"mysite.com\" {\n type master;\n file \"mysite.com.fwd\";\n allow-update { none; };\n};\n
}
" test.conf
Structure //,//
represents a sample of a range from a line with a matching pattern to another. In our case this is a 2 line pattern and we want to skip the first line, here goes /file*/n
. And then we add our block on the second and second lines, starting with a blank line.
Some useful approaches are also here: How to compile a block of text with a specific pattern?
source to share
Aspirating the following codes into "my_file" and replacing "^" instead of new lines to get one big line. We can now match the pattern "file "named.ca";
and then replace with new codes after that. Then you convert "^" back to newline characters "\ n".
cat 'my_file'|tr '\n' '^'|sed 's#//There are more lines up here- zone.*\(file "named.ca"\).*#\1 zone "mysite.com" {\n type master;\n file "mysite.com.fwd";\n allow-update { none; }; };\n#g'|tr '^' '\n'
results
//There are more lines up here
zone "." IN {
type hint;
file "named.ca";
};
zone "mysite.com" {
type master;
file "mysite.com.fwd";
allow-update { none; };
};
//There are more lines below here
source to share