-1

I've been trying to write a sed command to substitute a single word on single line, preserving all the leading white spaces and words.

e.g. From:

<Attr name="x" value="yes"/>

To:

<Attr name="x" value="no"/>

I know that I could just rewrite the entire line but I'd prefer a more elegant way to do it. Thanks!

fedorqui
  • 275,237
  • 103
  • 548
  • 598
mr.G
  • 167
  • 1
  • 1
  • 10

3 Answers3

4

I think without adding more specific requirement this simple solution should be fine:

sed 's/"yes"/"no"/'
Lajos Veres
  • 13,595
  • 7
  • 43
  • 56
  • You might want to change it to `s/"yes"/"no"` or `s/\/no` so you wouldn't change anything else accidentally. – Shahbaz Jan 15 '14 at 16:04
  • Thank you very much for your answer! But I think this wouldn't be an effective solution, as (my fault I didn't explain it) the file contains multiple entries and your solution would change the entire file. – mr.G Jan 16 '14 at 10:05
  • You can add the target line number before the s. – Lajos Veres Jan 16 '14 at 10:15
1

You can't parse XML with regexes. Use an XML processing tool. To replace the value for Attr nodes where name is "x" and value is "yes" you can use a tool like xmlstarlet:

echo '<doc>
  <Attr name="x" value="yes"/>
  <Attr name="y" value="yes"/>
  <Attr name="x" value="maybe"/>
</doc>' |
xmlstarlet ed -u '//Attr[@name="x"][@value="yes"]/@value' -v "no"
<?xml version="1.0"?>
<doc>
  <Attr name="x" value="no"/>
  <Attr name="y" value="yes"/>
  <Attr name="x" value="maybe"/>
</doc>
Community
  • 1
  • 1
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • I've not tried it yet, but it seems the best solution and the most flexible! Thank you very much!!! – mr.G Jan 16 '14 at 10:06
0

Lajos' solution will rewrite many occurences of word in file - that's probably not what you want.

Following sed invocation will replace first occurence of "yes" to "no" inside file.xml only in line 3:

sed -i 3s/yes/no/ file.xml
Patryk Obara
  • 1,847
  • 14
  • 19