Linux环境下如何用sed提取包含首尾匹配字符串的XML子元素
Hey Jim, let's get that full <l7:RevocationCheckingPolicy> block extracted properly! You're almost there—here are two straightforward ways to fix this, depending on your preference:
1. Simplest Approach: Match Line Ranges (No Flattening Needed)
Instead of flattening the XML first, you can use sed's built-in range matching to directly output all lines from the opening tag to the closing tag. This avoids dealing with string replacement across the entire flattened line:
sed -n '/<l7:RevocationCheckingPolicy/,/<\/l7:RevocationCheckingPolicy>/p' response.xml
How this works:
-ntells sed to suppress default output (only print what we explicitly ask for)/<l7:RevocationCheckingPolicy/,/<\/l7:RevocationCheckingPolicy>/defines the range of lines to match: starting at the line containing the opening tag, ending at the line containing the closing tagptells sed to print all lines within that range
This will output the exact block you need, including both the opening and closing tags, without any extra steps.
2. Fixing Your Original Flattened String Method
If you still want to use your initial approach of flattening the XML first, you just need to adjust your sed capture group to include the opening and closing tags themselves. Here's the modified command:
sed ':a;N;$!ba;s/\n//g' response.xml | sed -e 's/.*\(<l7:RevocationCheckingPolicy.*<\/l7:RevocationCheckingPolicy>\).*/\1/'
What changed:
- In your original command, you captured everything between the tags with
\(.*\). Now we capture the entire tag block (including the tags) by moving them inside the capture group:\(<l7:RevocationCheckingPolicy.*<\/l7:RevocationCheckingPolicy>\) - The
.*before and after the capture group still matches all text outside the block, and we replace the entire line with just the captured group (\1)
Important Note:
This flattened approach uses sed's greedy matching, so if your XML has multiple <l7:RevocationCheckingPolicy> blocks, it will capture from the first opening tag to the last closing tag (combining them into one string). The line range method above is safer if you might have multiple blocks, as it will output each block separately.
内容的提问来源于stack exchange,提问作者jstack100

