views:

169

answers:

3

Hi volks,

I have a XML file with a lot of empty tag attributes. For instance:

<mytag id="">
  <ontent>aaa</content>
</mytag>
<mytag id="">
  <ontent>bbb</content>
</mytag>
<mytag id="">
  <ontent>ccc</content>
</mytag>

Now I want to replace id="" with e.g. id="2443" (id="[linenumber]")

I tried to do this with sed, but I did not get a successful result.

I hope someone here can help me :-)

A: 

You may want to try with awk instead. The line number is stored in NR variable.

mouviciel
+1  A: 

If you want to replace empty id="" with id="l" where l is the line number where the mytag is found you can do:

Edit:

Based on the comments:

perl -pe '$i++; s{id=""}{id="$i"}' < file.xml
codaddict
This will work provided that the XML input is not free-form but exactly as posted. Nit-pick: you can drop the `print` if you use `perl -pe` instead.
msw
If I'm not mistaken this would be better done with perl -ne /here be code/ < filename - for speeds sake, but otherwise spot on.
Mimisbrunnr
I dig the braces on the `s` operator. I always forget you can do that.
msw
Thx a lot for your answers :-) I could solve the problem.
+1  A: 

If you can guarantee that your XML - which can be free-form - is in the exact form you wrote, awk or perl could do the job far more simply than sed. Unicornaddict had something that will work, but I'd be a little more careful in the substitution line:

perl -pe '$i++; s{id=""}{id="$i"} if /^<mytag id="">/' filename.xml

If you can't guarantee that the XML is not free-form, you'd really have to parse it with a proper XML parser. Generalized XML cannot be parsed with regular expressions.

msw