You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux下查找XML文件指定String节点并替换内容的命令/脚本需求

Hey there! For editing specific <String> nodes in your XML file on Linux, you've got two solid options—one that's XML-aware (and highly recommended) and a quick text-based workaround for when your XML has a totally fixed format. Let me break them down:

1. Use xmlstarlet (The Reliable, XML-Friendly Choice)

This is the best approach because it actually understands XML structure, so it won't break if your file gets reindented or nodes wrap across lines. First, install it if you don't have it:

  • Debian/Ubuntu: sudo apt install xmlstarlet
  • RHEL/CentOS/Fedora: sudo dnf install xmlstarlet

Example 1: Update an attribute in the Converter node

Say you want to change the sn value of the Converter inside <String name="07.01.01-1">:

# Preview changes first (no file modification)
xmlstarlet edit --update "/Station/Inverter/String[@name='07.01.01-1']/Converter/@sn" --value "2116K000999" your_xml_file.xml

# Modify the file directly (add -L flag)
xmlstarlet edit -L --update "/Station/Inverter/String[@name='07.01.01-1']/Converter/@sn" --value "2116K000999" your_xml_file.xml

Example 2: Replace the entire Converter node

If you need to swap out the whole Converter element for a new one:

xmlstarlet edit -L --replace "/Station/Inverter/String[@name='07.01.01-1']/Converter" --value "<Converter sku='31570014-0900 B' sn='2116K000999' mac='548280000999' ts='01'/>" your_xml_file.xml

The XPath expression /Station/Inverter/String[@name='07.01.01-1'] precisely targets your desired <String> node—no guesswork involved.

2. Use sed (Only for Super Fixed-Format XML)

This is a text-based hack that only works if your XML nodes are exactly in the same line structure every time. It's fragile (will break if nodes wrap or indentation changes), but handy for quick one-offs.

For example, if your <String name="07.01.01-1"> line is immediately followed by its Converter line, you can use:

# Replace the sn value in the targeted String's Converter
sed -i '/<String name="07.01.01-1">/{n;s/sn="2116K000551"/sn="2116K000999"/}' your_xml_file.xml
  • /<String name="07.01.01-1">/ matches the line with your target String node
  • {n;...} tells sed to jump to the next line (the Converter line)
  • s/old-value/new-value/ replaces the specific attribute content
  • -i edits the file in-place

A quick warning:

Avoid using sed for XML unless you have no other choice. XML is structured data, and text tools can't account for valid variations in formatting.

内容的提问来源于stack exchange,提问作者lugger1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:12:00