简体   繁体   English

命令以获取xml文件的第二行并使用获取的名称重命名该文件

[英]Command to fetch 2nd line of xml file and rename the file with fetched name

I have an xml file names media.xml and it consist of: 我有一个名为media.xml的xml文件,它包含:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<table name="advisoryTable"/>
  <row>
      <field name="book">maths</field>
      <field name="book">science</field>
      <field name="book">eng</field>
  </row>
</table>

Is there any way where i can fetch "advisory table" name from xml file and rename my file from media.xml to advisory.xml 有什么办法可以从xml文件中提取"advisory table"名称,并将文件从media.xml重命名为advisory.xml。

Thank you in advance 先感谢您

I'm hoping that your <table> element isn't actually self-closing, so your XML is valid. 我希望您的<table>元素实际上不是自动关闭的,因此您的XML有效。 If so, you can extract the value of the name attribute using a tool such as xmllint : 如果是这样,您可以使用诸如xmllint的工具来提取name属性的值:

xmllint --xpath 'string(/table/@name)' media.xml

The output of this command is advisoryTable . 该命令的输出为advisoryTable You could pipe the output to sed to remove the Table part: 您可以将输出通过管道传递到sed,以删除Table部分:

xmllint --xpath 'string(/table/@name)' media.xml | sed 's/Table//'

If you're happy with the result, this could be used within a command substitution to rename your file: 如果您对结果满意,可以在命令替换中使用它来重命名文件:

mv media.xml "$(xmllint --xpath 'string(/table/@name)' media.xml | sed 's/Table//')"

I would be reluctant to encourage automatically renaming files in this way, as you run the risk of accidentally overwriting something. 我不愿意鼓励以这种方式自动重命名文件,因为这样可能会导致意外覆盖某些内容。 Perhaps it would be a better idea to copy the files instead, possibly using cp -n to avoid clobbering files that already exist with the same name. 也许最好改为复制文件,可以使用cp -n避免破坏已经存在的具有相同名称的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM