Bash匹配多行中的字符串并附加到上一行

时间:2015-04-09 16:33:59

标签: linux bash awk sed

我试图用这些行来翻译文本文件:

policy rule {
    source-address host1;
    destination-address host2;
    application http;
policy someotherrule {
    source-address any;
    destination-address [ host2 host3];
    application ssh;

分为:

policy rule { source-address host1; destination-address host2; application http;
policy someotherrule { source-address any; destination-address [ host2 host3]; application ssh;

所以基本上,如果一行以分号结尾,则将其附加到上一行。

我一直在玩sed / awk但是找不到可以获得所需输出的工作解决方案。

3 个答案:

答案 0 :(得分:0)

遵循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;

答案 1 :(得分:0)

这个简单的单行将做:

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;

答案 2 :(得分:0)

以下是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;

根据行是否以policy开头,它根据行开始设置更改行的输出。