-2

I have a file pom.xml, which needs to have the version with a SNAPSHOT appended to it. At times, the SNAPSHOT is missing, which results in the build failing. I'm trying to replace it with SNAPSHOT if it doesn't exist.

Actual:

<artifactId>package1</artifactId>
<version>1.0.0</version>

Desired:

<artifactId>package1</artifactId>
<version>1.0.0-SNAPSHOT</version>

Since the artifactId is not going to be the same across all the projects, I tried to search for a pattern that starts from </artifactId> to </version> and replace it with the SNAPSHOT text added to it. This has resulted in replacing the text till the last version available in pom.xml.

I've tried the following:

cat pom.xml | sed ':a;N;$!ba;1,/<\/artifactId>/s/<\/artifactId><version>[0-9]*.[0-9]*.[0-9]*<\/version>/<\/artifactId><version>1.0.0-SNAPSHOT<\/version>/g'

(Not working at all as it's unable to find the end of line).

cat common-pom.xml | sed ':a;N;$!ba;0,/<\/artifactId>/s/<\/artifactId>.*<\/version>/<\/artifactId><version>0.0.0-SNAPSHOT<\/version>/g'

(Is able to do the changes, but it's replacing all the text till the last version available in pom.xml).

How do I stop the replacement to the first occurrence in a multi line replacement?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Pranesh Vittal
  • 153
  • 2
  • 8
  • Actually, what keeps you from just making the substitutions on the lines starting with ``? – Benjamin W. Jan 17 '16 at 03:43
  • Since that there are so many in the pom.xml and the replacement needs to be done at only one place, I can't replace all of them. – Pranesh Vittal Jan 17 '16 at 16:19
  • @jonathan-lefflet, I did go through the question mentioned by you. I was caught up with the extra line that needs to be handled explicitly. I couldn't get it through. Please reconsider the downvote as my question is slightly different from the one mentioned. – Pranesh Vittal Jan 17 '16 at 16:21

1 Answers1

1

If I understood the question correctly, this should work:

sed -r '
    /<artifactId>/ {
        n
        s/(([0-9]+\.){2}[0-9])(<\/version>)/\1-SNAPSHOT\3/
    }
' infile

You read the complete file into sed before starting with replacements. This just looks for a line with <artifactId>, reads the next line (n) and makes the replacement there.

Also, instead of using cat to pipe to sed, you can just give the file to be processed as an argument to sed.

This works also without -r, but then all parentheses and braces would have to be escaped.

Example file:

<artifactId>package1</artifactId>
<version>1.0.0</version>           <-- should get SNAPSHOT
<artifactId>package1</artifactId>
<version>1.0.0-SNAPSHOT</version>  <-- already has SNAPSHOT
Somethingelse
<version>1.0.0</version>           <-- doesn't follow artifactId line

results in

<artifactId>package1</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>package1</artifactId>
<version>1.0.0-SNAPSHOT</version>
Somethingelse
<version>1.0.0</version>
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116