如何搜索和替换多行文本AWK

时间:2018-05-17 22:59:50

标签: bash awk sed

我有一个包含以下内容的文件(代码段) - 测试可以在文件中的任何位置。

More text here
Things-I-DO-NOT-NEED:
      name: "Orange"

      count: 8

      count: 10


Things-I-WANT:
      name: "Apple"

      count: 3

      count: 4

More text here

我想替换:(包括缩进)

Things-I-WANT:
      name: "Apple"

      count: 3

      count: 4

Things-I-WANT:
      name: "Banana"

      count: 7

使用awk / sed实现它的任何建议?谢谢!

1 个答案:

答案 0 :(得分:0)

您可以在awk

中执行此操作
#!/usr/bin/env awk

# Helper variable
{DEFAULT = 1}

# Matches a line that begins with an alphabet
/^[[:alpha:]]+/ { 
    # This matches "Things-I-WANT:"
    if ($0 == "Things-I-WANT:") {
        flag = 1
    }
    # Matches a line that begins with an alphabet and which is 
    # right after "Things-I-WANT:" block
    else if (flag == 1) {
        print "\tname: \"Banana\""
        print ""
        print "\tcount: 7"
        print ""
        flag = 0
    }
    # Matches any other line that begins with an alphabet
    else {
        flag = 0
    }

    print $0
    DEFAULT = 0
}

# If line does not begin with an alphabet, do this
DEFAULT {
    # Print any line that's not within "Things-I-WANT:" block
    if (flag == 0) {
        print $0
    }
}

您可以使用以下内容在bash中运行

$ awk -f test.awk test.txt

此脚本的输出将为:

More text here
Things-I-DO-NOT-NEED:
      name: "Orange"

      count: 8

      count: 10


Things-I-WANT:
    name: "Banana"

    count: 7

More text here

如您所见,Things-I-WANT:块已被替换。