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

2
  • 3
    What edit do you want to make? Commented Oct 12, 2009 at 11:58
  • the setting called local directory, its value Commented Oct 12, 2009 at 16:21

4 Answers 4

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  
Sign up to request clarification or add additional context in comments.

2 Comments

I don't have -L option to edit in place, what edition of xmlstartlet and unix are you using?
Ah, brilliant - the -L option was just what I was looking for.
13

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.

3 Comments

+1 to above comment for use of the word dandy. +1 to post for great reference.
But what about something that's installed by default?
@TomášZato, ...then you end up using Python (which has several XML modules built in).
-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.

1 Comment

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.
-4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.