osx - Using sed to change text between tags -
i can't figure out how change changeme
changed
in file myfile.xml
using sed, on mac.
<string name="mytag">changeme</string>
i tried:
sed -i -e "s/\(<string name=\"mytag\">\)\(<\/string>\)/\1changed\2/g" ./myfile.xml
but output silent. help?
there 2 problems:
you're using gnu sed syntax: in bsd sed, version used on osx,
-i
requires , argument, if empty string (to indicate no backup should created), you must use-i ''
(note-i''
not work technical reasons).- see here overview of differences between gnu , bsd sed.
you're not matching contents of element, as fedorqui points out in helpful answer.
- however, regular expression uses gnu syntax: quantifier
\+
(for one or more matches) not supported in bsd sed. - while can fix replacing
\+
posix-compliant\{1,\}
, suggest using extended regular expression-e
instead - see below.
- however, regular expression uses gnu syntax: quantifier
unless must remain posix-compliant (in case couldn't use -i
), recommend using -e
option activate support extended regular expressions:
- extended regular expressions more powerful , work more you're used other languages (especially respect
+
,?
, ,|
); notably: - the syntax becomes cleaner (no need
\
-escape chars. such(
,)
,{
, ,}
).
case in point: here's a corrected version of command using -e
:
sed -i '' -e 's/(<string name="mytag">)[^>]+(<\/string>)/\1changed\2/g' ./myfile.xml
note i've switched single quotes around sed script, generally better choice:
- you protect script possibly unwanted up-front interpretation (expansions) shell.
- you won't have
\
-escape"
instances.
Comments
Post a Comment