首页 > 解决方案 > 如何搜索和替换多行文本AWK

问题描述

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

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 实现它的任何建议?谢谢!

标签: bashawksed

解决方案


你可以这样做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:块已被替换。


推荐阅读