Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script to edit xml file

Tags:

bash

xml

editing

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

like image 903
Gabriel Solomon Avatar asked Oct 12 '09 11:10

Gabriel Solomon


People also ask

How do you modify an XML file?

Create a new XML or XSLT fileFrom the File menu, select New. The New File dialog box appears. Select XML File to create a new XML file; or, select XSLT File to create a new XSLT style sheet. Select Open.

How do I edit an XML file in Ubuntu?

To edit any config file, simply open the Terminal window by pressing the Ctrl+Alt+T key combinations. Navigate to the directory where the file is placed. Then type nano followed by the filename that you want to edit. Replace /path/to/filename with the actual file path of the configuration file that you want to edit.


2 Answers

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  
like image 114
lmxy Avatar answered Sep 19 '22 15:09

lmxy


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.

like image 25
Brian Agnew Avatar answered Sep 21 '22 15:09

Brian Agnew