如何使用awk在两个连续行的字符串之间插入文本

how to insert text between strings on two successive lines with awk

我有一个 yaml 文件,其中缺少一些行(-示例下的源和目标:),其中 word1 需要修复,但 word2 没问题。

 - dyu: word1
    alt:
    trans:
      - lang: fr
        detail: null
        speech:
          - type: null
            def:
              - gloss: gloss1
                note: null
                example:
  - dyu: word2
    alt:
    trans:
      - lang: fr
        detail: null
        speech:
          - type: null
            def:
              - gloss: gloss2
                note: null
                example:
                  - source: some example source
                    target: some example target
  - dyu: word3

我使用以下方法插入缺失的文本:

awk -i inplace -v data="                  - source:\n                    target:" '/example:/ {f=1} /- dyu:/ && f {print data; f=0}1' $file 

但问题是即使文本存在,它也会插入文本。我需要在 example:\n - dyu 之间添加缺少的文本 exactly,而不是在 target: something\n -dyu.

之间

期望的输出:

 - dyu: word1
    alt:
    trans:
      - lang: fr
        detail: null
        speech:
          - type: null
            def:
              - gloss: gloss1
                note: null
                example:
                  - source: 
                    target: 
  - dyu: word2
    alt:
    trans:
      - lang: fr
        detail: null
        speech:
          - type: null
            def:
              - gloss: gloss2
                note: null
                example:
                  - source: some example source
                    target: some example target
  - dyu: word3

我怎样才能做到这一点?

这可能是您要找的:

awk -v data='                  - source:\n                    target:' \
    'f { if (/- dyu:/) print data; f=0 } /example:/ {f=1} 1
     END { if (f) print data }' file
$ cat tst.awk
example != "" {
    if ( !/- source:/ ) {
        sub(/[^[:space:]].*/,"",example)
        print example "  - source:"
        print example "    target:"
    }
    example = ""
}
=="example:" {
    example = [=10=]
}
{ print }

$ awk -f tst.awk file
 - dyu: word1
    alt:
    trans:
      - lang: fr
        detail: null
        speech:
          - type: null
            def:
              - gloss: gloss1
                note: null
                example:
                  - source:
                    target:
  - dyu: word2
    alt:
    trans:
      - lang: fr
        detail: null
        speech:
          - type: null
            def:
              - gloss: gloss2
                note: null
                example:
                  - source: some example source
                    target: some example target
  - dyu: word3

如果您愿意,将正则表达式 !/- source:/ 更改为 /- dyu:/,脚本将以与您的示例输入相同的方式运行,但恕我直言,这不如仅测试 source 之后是否存在那么可靠example与否。