Search code examples
macossedbsd

Sed - Conditionally match and add additional string after the find


Let's say I have a line like this in a file "config.xml"

<widget android-packageName="com.myproject" android-versionCode="12334" ios-CFBundleIdentifier="com.myproject" ios-CFBundleVersion="12334" version="1.5.2" versionCode="1.5.2" xmlns="http://www.w3.org/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cdv="http://cordova.apache.org/ns/1.0">

And I want to use a line of command in sed to change it into this, which is adding ".1" after the current version numbers:

<widget android-packageName="com.myproject" android-versionCode="12334" ios-CFBundleIdentifier="com.myproject" ios-CFBundleVersion="12334" version="1.5.2.1" versionCode="1.5.2.1" xmlns="http://www.w3.org/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cdv="http://cordova.apache.org/ns/1.0">

Assuming the version number could change, which means I would likely need to match it as a string between "version="" and """ first then add something after. How should I achieve that?


Attempted code that was (wrongly) shown in the form of an answer:

sed -i '' -e 's/\" versionCode=\"/\.1\" versionCode=\"/g' config.xml
sed -i '' -e 's/\" xmlns=\"/\.1\" xmlns=\"/g' config.xml

Solution

  • You may use this sed to append .1 in version number of any field name starting with version:

    sed -i.bak -E 's/( version[^=]*="[.0-9]+)/\1.1/g' file
    

    Output:

    <widget android-packageName="com.myproject" android-versionCode="12334.1" ios-CFBundleIdentifier="com.myproject" ios-CFBundleVersion="12334" version="1.5.2.1" versionCode="1.5.2.1" xmlns="http://www.w3.org/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cdv="http://cordova.apache.org/ns/1.0">

    Breakup:

    • (: Start capture group
      • version: natch text version
      • [^=]*: match 0 or more of any character that is not =
      • =: match a =
      • ": match a "
      • [.0-9]+: match 1+ of any character that are digits or dot
    • ): End capture group