【发布时间】:2014-09-04 06:18:17
【问题描述】:
我第一次尝试使用 sed 进行多行替换。我发现了一些很好的建议(general multiline help 和multiline 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