[英]sed conditional branching with multiline section
我第一次尝试用sed进行多行替换。 我在那里找到了两个很好的指针( 一般的多行帮助和两个字符串之间的多行 )。 使用它作为启动器,我有以下命令:
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>
我哪里做错了?
多行是由于“问题”导致在strem / file输入上逐行保存工作,而不是整个过程。 在您的情况下,您将处理一包线,但一次仍处理一线,而不是将其视为一个块
/ 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.