2014-09-04 43 views
1

我想多線替換與第一次sed。我在那裏找到了幾條好的指針(general multiline helpmultiline between two strings)。使用這個作爲首發,我有以下命令: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> 

我哪裏出錯了?

回答

0

多行是由於「問題」,sed工作逐行在strem /文件輸入,而不是作爲一個整體。 在你的情況下,你對待一包行,但仍然一行一行,而不是作爲一個塊

/startBlock /,/ EndBlock /意思就是,處理這些2分隔符內的所有行,而不是組中的塊大塊

這裏是適應提出

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