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

Unix中多行内容替换:为XML主记录添加分隔符(sed命令)

Sed Solution to Add Separator at End of XML Main Records

Got it, let's work through how to use sed to insert a separator right after your XML main records end in a Unix environment. I'll cover two common scenarios based on your XML structure.

Scenario 1: Exact Single-Line End Tag

If your main record closes with a clear, single-line tag like </MainRecord>, you can use a straightforward substitution. The trick is to match the end tag and append your separator right after it.

Command:

# Use | as delimiter to avoid escaping / in XML tags
sed 's|</MainRecord>|&\
---XML-RECORD-SEPARATOR---|' your_input.xml

Breakdown:

  • s|pattern|replacement|: Sed's substitution command, using | instead of / to avoid escaping the / in </MainRecord>.
  • &: Represents the exact text we matched (</MainRecord>), so we keep the original tag intact.
  • The backslash followed by a newline tells sed to add a line break before the separator, making it cleanly appear on its own line after the end tag.

Scenario 2: Target a Full Record Block

If you need to ensure the separator is added only after the full main record block (from opening <MainRecord> to closing </MainRecord>), use sed's range address feature to target the entire block, then append the separator specifically at the closing tag.

Command:

sed '/<MainRecord>/,/<\/MainRecord>/ {
  /<\/MainRecord>/a\
---XML-RECORD-SEPARATOR---
}' your_input.xml

Breakdown:

  • /<MainRecord>/,/<\/MainRecord>/: Defines the range of lines from the opening main record tag to the closing one.
  • { ... }: Groups commands to run only on lines within that range.
  • /<\/MainRecord>/a\: The a command appends the following text right after the line matching </MainRecord>.

Modify the File In-Place

To update your XML file directly instead of printing to stdout, use the -i flag (note: BSD sed (like on macOS) requires an empty string argument for -i):

# GNU sed (Linux)
sed -i 's|</MainRecord>|&\n---XML-RECORD-SEPARATOR---|' your_input.xml

# BSD sed (macOS)
sed -i '' 's|</MainRecord>|&\
---XML-RECORD-SEPARATOR---|' your_input.xml

Important Notes

  • Make sure your closing main record tag is unique—don't use this if there are nested tags with the same name (e.g., a child </MainRecord> inside the main one).
  • For complex XML structures (like multi-line tags or namespaces), sed might not be the most robust tool. In those cases, consider XML-specific tools like xmllint or xsltproc, but if you need a pure sed solution, double-check your pattern matching.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:28:05