简体   繁体   中英

sed - replace multiple lines (a whole block of text)

I have the following text that I'm operating on:

... other stuff here..

options { chain_hostnames(off); flush_lines(0); use_dns(no); use_fqdn(no);
          owner("root"); group("log"); perm(0640); stats_freq(0);
          bad_hostname("^gconfd$");
};

... other stuff here..

I need to use sed in order to add log_fifo_size(30000); as a new line making my text look like:

... other stuff here..

options { chain_hostnames(off); flush_lines(0); use_dns(no); use_fqdn(no);
          owner("root"); group("log"); perm(0640); stats_freq(0);
          bad_hostname("^gconfd$");
          log_fifo_size(30000);
};

... other stuff here..

I understand HOW regexp work, just not confident enough to use it. So any explanation of syntax and or any help at all is greatly appreciated!

I've tried the following:

$sed -e 's/options.*/TEST/g' syslog.conf
$sed -e '/options.*/ {N; s//TEST/g}' syslog.conf

Both of which got me close, but not close enough.

sed -e '/options.*/ {N;N; s//options {/g}' syslog.conf

This is the closest i've gotten. But since i don't know the ammount of rows between options { and } this is a bit tricky.

I've followed countless of guides but I've always had a rough time learning by documentation. I like a good example to follow, so I guess i'm asking if i can get help to create an example out of my situation which i can use to learn the basics and later on the fundamentals of regex/sed.

从您的示例中,您正在插入一行,您可以使用i

sed '/};/i\          log_fifo_size(30000);' 
sed '/options {/,/};/ {
   s/};/log_fifo_size(30000);\
&/
   }' YourFile

take the section starting with options { until }; change line }; with log_fifo_size(30000);\\n};

it does not align the log... with rest of section but it can be done with some more code

This assume that section is close with a }; and no }; ar in the section content

This might work for you (GNU sed):

sed '/^options/,/^};/{/};/{x;s/\S.*/log_fifo_size(30000);/;x;H;g};h}' file

This works on the options part of the file. Copies each line into the hold space and when it encouters the last line, replaces all but the front spaces in the copy of the previous line with the required string. Then appends the last line and prints out the two lines together.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM