如果下一行与模式匹配,则插入分号



我一直在为以下问题而苦苦挣扎。我有大约 800 个这种格式的文件,我一直在尝试编写一个 sed/awk 脚本来修复。

该文件将如下所示

symbols
    V2:1.2
    v1:1.1
locks; strict;

基本上,如果下一行包含单词 locks; strict;,我需要对其进行转换以在最后一行符号中添加分号。

输出应如下所示

symbols
    V2:1.2
    v1:1.1;
locks; strict;
可以使用

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序列是在模式空间中一次保留两行的惯用方法:加载下一行,打印到换行符,删除到换行符。

您可以使用

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}

另一种awk方法是:

awk 'BEGIN{RS="nlocks; strictn";ORS=";nlocks; strictn"}{print}' your_file

另一种awk方法:

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

最新更新