简体   繁体   English

sed-替换多行(一整段文字)

[英]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); 我需要使用sed来添加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. 但是由于我不知道 options {}之间的行数 ,所以有点棘手。

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. 我喜欢一个很好的例子,所以我想我想问的是我是否可以从我的情况中创建一个例子来帮助我学习基础知识,然后再学习regex / sed的基础知识。

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

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

take the section starting with options { until }; 以从options {};开始的部分}; change line }; 换行}; with log_fifo_size(30000);\\n}; 使用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 本节内容中的ar

This might work for you (GNU sed): 这可能对您有用(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. 这适用于文件的options部分。 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. 然后追加最后一行并一起打印出两行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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