使用AWK在模式之间添加文本

时间:2016-09-19 19:28:28

标签: awk

INPUT:

Define {
     abcd **pattern**
     xyzs wedlenle
     jqwd sadjkjnd 
} 
Define { 
     abcd asjdanja
     xyzs wedlenle
     jqwd sadjkjnd
}
Define {
     abcd **pattern**
     xyzs wedlenle
     jqwd sadjkjnd 
     ADD LINE HERE
}   

预期输出:

Define {
     abcd **pattern**
     xyzs wedlenle
     jqwd sadjkjnd 
     ADD LINE HERE
} 
Define { 
     abcd asjdanja
     xyzs wedlenle
     jqwd sadjkjnd
}
Define {
     abcd **pattern**
     xyzs wedlenle
     jqwd sadjkjnd 
     ADD LINE HERE
} 

需要** ADD LINE **在“}”之前定义块。

转角案例: 1)多个模式 - 在循环中使用 2)增加的线应该是空间领先的 3)只有在同一块中不存在的情况下才添加行。

2 个答案:

答案 0 :(得分:1)

$ cat test.awk
BEGIN {
    RS=ORS="}"
} 
{   # BELOW         don't print:       print:
    print $0 ($0 !~ /ADD LINE/ && $0 ~ /PATTERN/? "     ADD LINE HERE\n" :"")
}

测试文件:

$ cat > test.txt
Define {
     has PATTERN
     no add line
     so add it here
} 
Define {
     has PATTERN
     has ADD LINE
     dont add it here
} 
Define { 
     no pattern
     no add line
     dont add it here
}    

试运行:

$ awk -f test.awk test.txt
Define {
     has PATTERN
     no add line
     so add it here
     ADD LINE HERE
} 
Define {
     has PATTERN
     has ADD LINE
     dont add it here
} 
Define { 
     no pattern
     no add line
     dont add it here
}    

答案 1 :(得分:1)

$ awk '
/}/ {
    if (f) {
        sub(/[^[:space:]].*/,"",prev)
        print prev "ADD LINE HERE"
        f=0
    }
}
/pattern/ { f=1 }
{ prev=$0; print }
' file
Define {
     abcd **pattern**
     xyzs wedlenle
     jqwd sadjkjnd
     ADD LINE HERE
}
Define {
     abcd asjdanja
     xyzs wedlenle
     jqwd sadjkjnd
}