[英]Bash match string in multiple lines and append to previous line
I'm trying to turn a text file with these lines: 我正在尝试使用以下行来打开文本文件:
policy rule {
source-address host1;
destination-address host2;
application http;
policy someotherrule {
source-address any;
destination-address [ host2 host3];
application ssh;
Into: 进入:
policy rule { source-address host1; destination-address host2; application http;
policy someotherrule { source-address any; destination-address [ host2 host3]; application ssh;
So basically, if a line ends with a semicolon, append it to the previous line. 因此,基本上,如果一行以分号结尾,请将其附加到前一行。
I've been playing with sed/awk but haven't found a working solution to get the desired output. 我一直在与sed / awk玩,但是还没有找到可行的解决方案来获得所需的输出。
Following gnu-awk should work: 以下gnu-awk应该可以工作:
awk -v RS='(^|\n)[^\n]*[^;]\n' 'NF{s=p $0; gsub(/(^|\n+)[[:blank:]]+/, " ", s); print s}
{p=RT}' file
policy rule { source-address host1; destination-address host2; application http;
policy someotherrule { source-address any; destination-address [ host2 host3]; application ssh;
This simple one-liner will do: 这个简单的单行代码可以做到:
perl -p0e 's/\n\s+/ /g' file
policy rule { source-address host1; destination-address host2; application http;
policy someotherrule { source-address any; destination-address [ host2 host3]; application ssh;
Here is an awk
solution: 这是一个awk
解决方案:
awk '{$1=$1;printf (/^policy/ &&NR>1?RS:"")"%s",$0} END {print ""}' file
policy rule {source-address host1;destination-address host2;application http;
policy someotherrule {source-address any;destination-address [ host2 host3];application ssh;
It sets the change the output of the line depending if line starts with policy
or not. 它根据行是否以policy
开头来设置更改行的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.