Daniel Ionescu
Daniel Ionescu

Reputation: 51

Replace a string between two strings with regex

I have the following regex:

(\<parent\>(?s).*\<version\>).*(\<\/version\>(?s).*\<\/parent\>)

Which should work on the following text:

<name>CTR</name>

<!-- Parent -->
<parent> 
    <groupId>cxxdsds</groupId>
    <artifactId>c222</artifactId>       
    <version>5.0.0-REPO</version>
</parent>

<scm>

I want to replace the string between <version> and <version>. But my sed does not work: sed -i 's/(\<parent\>(?s).*\<version\>).*(\<\/version\>(?s).*\<\/parent\>)/\1xxxxxxx\2/g' pom.xml Any ideas?

Upvotes: 0

Views: 364

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133760

With your shown samples, you could try following sed code for substitution.

sed 's/\(<version>\)[^<]*\(<.*\)/\1xxxxxxx\1/' Input_file

Explanation: Simple explanation would be, using sed's back reference capability to store <version> and </version> in 2 different capturing groups and then while performing substitution adding new value xxxxxxx between 2 capturing groups as per required output.

2nd solution: Using awk in case you want to look for tag <parent> as per shown samples and you want to replace version only in it then try following.

awk '
/<parent>/ { found=1 }
/<version>/{
  line=$0
  next
}
/<\/parent>/ && found{
  if(line){
    sub(/>.*</,">xxxxxxx<",line)
  }
  print line ORS $0
  line=found=""
  next
}
1
' Input_file

Upvotes: 1

Related Questions