2016-05-31 30 views
1

我一直在努力解决以下问题。我有大约800个这种格式的文件,我一直试图编写一个sed/awk脚本来修复。如果下一行匹配模式,插入分号

该文件将如下所示

symbols 
    V2:1.2 
    v1:1.1 
locks; strict; 

基本上,我需要转换到一个分号添加到符号的最后一行,如果下一行包含单词locks; strict;

输出应该看起来像

symbols 
    V2:1.2 
    v1:1.1; 
locks; strict; 
+0

'sed'N;/\ nlocks;严格;/{S/\ N /; &/}; P; D'' – 123

回答

1

可以使用N命令加载下一行到模式空间,如果图案换行后包含locks; strict;,换行符前插入一个分号:

$ sed 'N;s/\n.*locks;.*strict.*/;&/;P;D' infile 
symbols 
    V2:1.2 
    v1:1.1; 
locks; strict; 

locks; strict;这一行的正则表达式的写法使得它与两个词之间(或之前和之后)之间的内容无关,例如word locks; more words strict; even more words。如果如果行只包含locks; strict;它应该只匹配,该命令必须改为

sed 'N;s/\nlocks; strict/;&/;P;D' infile 

&重复完全吻合,所以我们甚至都不需要捕捉组在这里。 N;P;D序列是在模式空间中一次保持两行的惯用方式:加载下一行,打印到换行,删除到换行。

+0

这不适用于非平行线......人们过早地投票。 – 123

+0

@ 123 Oops ...已更新。 –

+0

@ 123为什么你没有发布你的答案,因为答案,而不是评论? –

1

您可以使用awk

awk '/locks; strict;/{l=l";"}NR>1{print l}{l=$0}END{print l}' file 

更好地在多版本的解释:

# script.awk 

# If the pattern matches we append an ; to the last line (l) 
/locks; strict;/ { 
    last = last";" 
} 

# If NR is greater than 1 print the last line. 
# Note that in the first line, `last` is still undefined 
# at this point. 
NR>1 { 
    print last 
} 

# Set last line to current line 
{ last = $0 } 

# At the end of input print the last line 
END {print last} 
0

又一个awk方法是:

awk 'BEGIN{RS="\nlocks; strict\n";ORS=";\nlocks; strict\n"}{print}' your_file 

另一个awk方式做到这一点:

awk 'BEGIN{RS="^$"}{$0=gensub(/\nlocks; strict\n/,";\nlocks; strict\n","g",$0); printf "%s",$0}' your_file