pizzafilms
pizzafilms

Reputation: 4019

How to replace version number in file?

I'd like to replace the version number in the pkg-ref lines of my xml file which looks like this:

<?xml version="1.0" encoding="UTF-8"?>
  <pkg-ref id="com.mycomp.pkg.foo1" version="1.1.15" auth="Root" installKBytes="">#foo1.pkg</pkg-ref>
  <pkg-ref id="com.mycomp.pkg.foo2" version="1.1.15" auth="Root" installKBytes="">#foo2.pkg</pkg-ref>

I tried this:

#!/bin/sh

NEW_VERSION="1.2.0"

sed -ie "s/version=\"*.*.*\"/version=\"$NEW_VERSION\"/" foo.xml

...but it removes part of the rest of the line and also replaces the xml version which is only 2 digits and which I don't want...leaving me with this:

<?xml version="1.2.0"?>
  <pkg-ref id="com.mycomp.pkg.foo1" version="1.2.0">#foo1.pkg</pkg-ref>
  <pkg-ref id="com.mycomp.pkg.foo2" version="1.2.0">#foo2.pkg</pkg-ref>

What should my sed line be?

Thank you.

Upvotes: 2

Views: 6550

Answers (2)

revo
revo

Reputation: 48751

You could use restrictive regular expressions using negated character classes:

sed -ie "s/\(<pkg-ref [^>]*version=\"\)[^\"]*\"/\1$NEW_VERSION\"/" foo.xml

Breakdown:

  • \( Start of capturing group #1
    • <pkg-ref□ Match <pkg-ref□ literally, denotes a space character
    • [^>]* Up to first closing >
    • version=\" Match version=" literally (possible backtracks here)
  • \) End of CG #1
  • [^\"]*\" Match up to and including first double quotation mark

In replacement string \1 is a back-reference to first capturing group.

Upvotes: 6

builder-7000
builder-7000

Reputation: 7657

You can do:

sed -i "s/version=\"[^\"]*\"/version=\"${NEW_VERSION}\"/g" foo.xml

Upvotes: 0

Related Questions