Unix中多行内容替换:为XML主记录添加分隔符(sed命令)
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\: Theacommand 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),
sedmight not be the most robust tool. In those cases, consider XML-specific tools likexmllintorxsltproc, but if you need a pure sed solution, double-check your pattern matching.
内容的提问来源于stack exchange,提问作者Shriraj

