3

When you follow the doc:

xmlstarlet edit --help

you can read that --var can be used to declare a XPath expression as a variable.

Generating moc file:

cat<<EOF > /tmp/file.xml
<root>
<elt>x</elt>
<!-- comment -->
<elt>y</elt>
<!-- other comment -->
</root>
EOF

This one works, without variables:

xmlstarlet edit \
    --var xp '//elt/following::comment()' \
    -a '//elt/following::comment()' -t elem -n p -v 'some new text' \
    -a '//elt/following::comment()' -t elem -n p -v 'some other text' \
/tmp/file.xml

This one doesn't edit with variables:

xmlstarlet edit \
    --var xp '//elt/following::comment()' \
    -a xp -t elem -n p -v 'some new text' \
    -a xp -t elem -n p -v 'some other text' \
/tmp/file.xml

What does I miss to use variable?

1 Answers1

5

Use '$xp' to reference your variable:

xmlstarlet edit \
    --var xp '//elt/following::comment()' \
    -a '$xp' -t elem -n p -v 'some new text' \
    -a '$xp' -t elem -n p -v 'some other text' \
/tmp/file.xml
Freddy
  • 25,172
  • 1
  • 21
  • 60
  • Not obvious, an example in the doc could have been interesting, thanks – Mévatlavé Kraspek Feb 28 '23 at 09:16
  • 1
    @MévatlavéKraspek It is mentioned in the documentation of the `--var` option in `xmlstarlet select --help`, but the same option has a shortened help text in `xmlstarlet edit --help`. It works the same in `select` as in `edit` though. – Kusalananda Feb 28 '23 at 10:24