bash bash脚本编辑xml文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1554143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:15:50  来源:igfitidea点击:

bash script to edit xml file

xmlbashediting

提问by Gabriel Solomon

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

我想编辑一个 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?

从 bash 脚本执行此操作的最简单方法是什么?

Thanks

谢谢

回答by lmxy

Using xmlstarlet:

使用 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  

回答by Brian Agnew

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.

根据您想要做什么,您可能想要使用一些特定于 XML 的工具(处理字符编码、维护 XML 格式良好等)。您可以使用普通的面向行的工具,但除非您小心(或做一些无关紧要的事情),否则您很容易创建不兼容的 XML。

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

我使用XMLStarlet命令行集。它是一组专门用于解析/操作 XML 的命令行实用程序。

回答by Gabriel Solomon

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.

大多数人可能会使用 sed 从 bash 脚本进行行编辑。如果你真的关心解析 XML,那么使用像 Perl 这样的东西,它有一个现成的 XML 解析器。

回答by dimba

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

丑陋/不安全但有时最简单的是从 bash 调用 sed/perl/awk