使用sed命令替换XML中<l_num>标签内数字失败,求排查原因
Fixing Your Sed Command for XML
<l_num> Tag Replacement Let's break down what's wrong with your original sed command and fix it to meet your requirements:
Issues with the Original Command
- Incorrect word boundaries (
): Thematches word boundaries (between alphanumeric/underscore and non-word characters), but<l_num>ends with>(a non-word character) and the number starts right after it—there's no word boundary here. Same issue with the closing</l_num>: the number ends before<, which is also not a word boundary, so the trailingdoesn't work. - Misused line anchors (
^/$): You used line start (^) and line end ($) anchors, but the<l_num>tag and its content are just part of a line, not the entire line. This makes the regex fail to match anything at all. - Unrestricted number matching: The regex
[0-9]([0-9]*)matches any number (like 17, 100, etc.), not just the 0-16 range you need. - Minor typo in closing tag: Your expected output uses
</l_num>, but the command wrote</lnum>(missing the underscore)—easy fix once the matching works.
Corrected Sed Command for 0-16 Replacement
To match only valid 0-16 values (no leading zeros for single-digit numbers) and replace them with 5, use this command:
sed -i -r 's/<l_num>(0|[1-9]|1[0-6])<\/l_num>/<l_num>5<\/l_num>/g' test.xml
Regex Breakdown:
(0|[1-9]|1[0-6]): This grouped pattern explicitly matches:0(the single-digit zero)[1-9](single-digit numbers 1-9, no leading zeros)1[0-6](two-digit numbers 10-16, covering the upper end of your range)
- We directly match the full
<l_num>...</l_num>tag structure without incorrect boundaries or line anchors, ensuring we only target valid tag content.
Handling the "05" Replacement Case
If you want to skip modifying the file entirely when the replacement value is 05 (since 05 violates the "no leading zeros for single-digit numbers" rule), wrap the sed command in a shell condition to validate the replacement value first:
REPLACE_VALUE="05" # Check if the replacement value is valid (0-16, no leading zeros) if [[ "$REPLACE_VALUE" =~ ^0$|^[1-9]$|^1[0-6]$ ]]; then sed -i -r "s/<l_num>(0|[1-9]|1[0-6])<\/l_num>/<l_num>$REPLACE_VALUE<\/l_num>/g" test.xml else echo "Replacement value '$REPLACE_VALUE' is invalid (no leading zeros for single digits, must be 0-16). No changes made." fi
This way, if you set REPLACE_VALUE to 05, the condition fails, and the file remains untouched.
内容的提问来源于stack exchange,提问作者skrowten_hermit
相关产品推荐
相关产品推荐

