【问题标题】:sed conditional branching with multiline section具有多行部分的 sed 条件分支
【发布时间】:2014-09-04 06:18:17
【问题描述】:

我第一次尝试使用 sed 进行多行替换。我发现了一些很好的建议(general multiline helpmultiline between two strings)。使用它作为启动器,我有以下命令:

sed '
/<dependency>/,/<\/dependency>/ { # Find a set of lines for a dependency
    s/\(<artifactId>\)m[^<]*\(<\/artifactId>\)/\1ARTIFACTID\2/ # Substitute if artifactId starts with 'm'
    t depend-update # If we substituted, go to depend-update.  Otherwise, continue
    :depend-unchanged
    s/\(<groupId>\)[^<]*\(<\/groupId>\)/\1CHANGE_A\2/ # Change groupId to have 'A'
    b # branch to end
:depend-update
    s/\(<groupId>\)[^<]*\(<\/groupId>\)/\1CHANGE_B\2/ # Change groupID to have 'B'
    b # branch to end
}
' \
inputfile.xml

我的输入文件有以下内容:

<dependency>
    <groupId>foo</groupId>
    <artifactId>test.a</artifactId>
</dependency>
<dependency>
    <groupId>bar</groupId>
    <artifactId>mytest.a</artifactId>
</dependency>
<dependency>
    <groupId>baz</groupId>
    <artifactId>test.b</artifactId>
</dependency>

不幸的是,对于所有部分,我都得到“CHANGE_A”。据我了解,这意味着 sed 总是认为第一个替换什么也没做,即使它确实做了。结果是:

        <dependency>
            <groupId>CHANGE_A</groupId>
            <artifactId>test.a</artifactId>
        </dependency>
        <dependency>
            <groupId>CHANGE_A</groupId>
            <artifactId>ARTIFACTID</artifactId>
        </dependency>
        <dependency>
            <groupId>CHANGE_A</groupId>
            <artifactId>test.b</artifactId>
        </dependency>

我哪里做错了?

【问题讨论】:

    标签: sed branch conditional


    【解决方案1】:

    多行是由于 sed 在 strem/文件输入上逐行工作而不是作为一个整体的“问题”。 在你的情况下,你处理一包线,但一次仍然是一条线,而不是一个块

    /startBlock/,/EndBlock/ 意思是,把这两个分隔符内的所有行都处理,而不是将块分组到一个大块中

    这是建议的改编

    sed '
    /<dependency>/,\#</dependency># {
    # load into the buffer
        /<dependency>/ h;/<dependency>/ !H
        \#</dependency># {
    # At end of block, load the buffer and work on it
        g
    
    # Find a set of lines for a dependency
            s/\(<artifactId>\)m[^<]*\(<\/artifactId>\)/\1ARTIFACTID\2/ # Substitute if artifactId starts with 'm'
            t depend-update # If we substituted, go to depend-update.  Otherwise, continue
    :depend-unchanged
            s/\(<groupId>\)[^<]*\(<\/groupId>\)/\1CHANGE_A\2/ # Change groupId to have 'A'
    # branch to end
            b # branch to end
    :depend-update
            s/\(<groupId>\)[^<]*\(<\/groupId>\)/\1CHANGE_B\2/ # Change groupID to have 'B'
    # branch to end
            b
            }
        }
    ' \
    inputfile.xml
    

    【讨论】:

      猜你喜欢
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 2019-08-20
      相关资源
      最近更新 更多