我第一次尝试使用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>
不幸的是,对于所有部分,我得到了&#34; CHANGE_A&#34;。据我了解,这意味着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>
我哪里出错了?
答案 0 :(得分:0)
多行是由于“问题”导致在strem /文件输入上逐行工作而不是整体。 在你的情况下,你处理一个行,但一次仍然是1行而不是块
/ startBlock /,/ EndBlock /表示只是,处理那些2个分隔符内的所有行,而不是将块分组在1个大块中
以下是提议的改编
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