6

I need to replace the versionName in a xml file from a shell script using sed.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.sed"
    android:versionCode="1"
    android:versionName="UNKNOWN VERSION NAME">

I've gotten so far as to search for a line containing versionName but how to tell sed to replace everything within the double quotes coming directly after versionName?

sed -i .old '/versionName/ s/WHAT TO WRITE?/NEW VERSION NAME/' AndroidManifest.xml
mach
  • 8,315
  • 3
  • 33
  • 51

3 Answers3

8

Replace not-", like this:

sed -i .old '/android:versionName/ s/="[^"][^"]*"/="NEW VERSION NAME"/' AndroidManifest.xml
lcd047
  • 5,731
  • 2
  • 28
  • 38
  • Note that this depends on the line-breaks as entered in the question, with one attribute per line. If the XML gets reformatted and the non-significant whitespace is collapsed, then you'll need the attribute name to be part of the match and replacement: `s/\(android:versionName\)="[^"]*"/\1="NEW VERSION NAME"/` (I've also changed to permit empty string - again, just in case. – Toby Speight Jun 04 '15 at 07:40
  • 1
    @TobySpeight Well, there's always [this warning](http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-reg). But assuming the OP has a tight control over how the XML is generated, it can still be done the easy way. – lcd047 Jun 04 '15 at 10:55
4

Considering the nature of xml and the version number, it is actually very safe to use a simpler command:

sed -i '/versionName/s/".*"/"NEW VERSION NAME"/' AndroidManifest.xml

P.S. in my opinion, it is very important to be able to simplify your shell script based on specific circumstances and reasonable assumptions.

Lungang Fang
  • 1,427
  • 12
  • 14
0
sed 's/\([[:blank:]]android:versionName="\)[^"]*"/\1Your New Value"/' YourFile
  • assuming that all section that have android:versionName will be changed
  • with GNU sed still better with replacing [[:blan:k]] by \(^\|[[:blank:]]\) (and a -i if direct modification avoiding temporary file)
NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43