Home > Software design >  Sed - Conditionally match and add additional string after the find
Sed - Conditionally match and add additional string after the find

Time:09-27

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?

CodePudding user response:

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

CodePudding user response:

It works with the following code, which is to match the small substring after it instead:

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