如何在Shell脚本中禁用特殊字符功能?Sed替换特殊字符串方法
Hey there! Let's get your sed substitution working properly. The key issue here is that your target string contains / characters, which are the default delimiter for sed's s command—sed is interpreting those / as part of the command syntax instead of literal characters. Here are two straightforward ways to fix this:
1. Use a Custom Delimiter (Recommended)
Instead of sticking with / as the separator for the s command, pick a character that doesn't appear in your search/replace strings (like #, |, or @). This lets you avoid escaping any special characters in your target string entirely.
For your case, here's the corrected command using # as the delimiter:
sed -i 's#%D/%M/%Y %H:%I:%S,%F000#%d/%m/%y %H:%i:%s,%f000#g' inputfile.txt
- We replaced the default
/delimiter with#for thescommand. Now, sed treats all/in your search and replace strings as literal characters, no escaping needed. - I removed the
\bword boundary markers from your original command because your target string isn't a "word" (it includes%and/), so\bwouldn't match correctly anyway.
2. Escape Special Characters
If you prefer to keep using / as the delimiter, you need to escape every / in your search and replace strings with a backslash (\/). This tells sed to treat them as literal characters instead of command separators:
sed -i 's/%D\/%M\/%Y %H:%I:%S,%F000/%d\/%m\/%y %H:%i:%s,%f000/g' inputfile.txt
This works, but it's more error-prone—especially if your string has lots of special characters to escape. The custom delimiter method is cleaner and easier to maintain.
Either approach will let you perform the exact replacement you need without sed misinterpreting the special characters in your string.
内容的提问来源于stack exchange,提问作者vijay Daggumati

