10

I want to edit the config file of a program that is an XML:

<software>
   <settings>
       ...
       <setting name="local directory" type="string">/home/username/</setting>
       ...
   </settings>
</software>

What is the easiest way to do this from a bash script?

Thanks

Community
  • 1
  • 1
Gabriel Solomon
  • 29,065
  • 15
  • 57
  • 79

4 Answers4

20

Using xmlstarlet:

xmlstarlet val -e file.xml
xmlstarlet ed -u "//settings/setting/@name" -v 'local directory2' file.xml
xmlstarlet ed -u "//settings[1]/setting/@name" -v 'local directory2' file.xml

# edit file inplace
xmlstarlet ed -L -u "//settings/setting/@name" -v 'local directory2' file.xml  
lmxy
  • 201
  • 2
  • 3
12

Depending on what you want to do, you may want to use some XML-specific tooling (to handle character encodings, to maintain XML well-formedness etc.). You can use the normal line-oriented tools, but unless you're careful (or doing something trivial) you can easily create non-compliant XML.

I use the XMLStarlet command line set. It's a set of command line utilities for specifically parsing/manipulating XML.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
-4

Most people would probably use sed to do line editing from a bash script. If you actually care about parsing the XML, then use something like Perl which has a ready XML parser.

  • This could be a way of solving the problem. But in that case please try to add some sample codes for that. Don't give vague sentences. – Arun Sooraj Oct 04 '17 at 04:12
-4

An ugly/unsafe but sometimes the easiest is to call sed/perl/awk from bash

dimba
  • 26,717
  • 34
  • 141
  • 196