如何使用sed命令替换变量中存储的文件路径
Let's break down why your sed command isn't working and get it sorted out quickly.
The Root Problems
You're hitting two main issues here:
- Your variable isn't storing the right path: When you defined
replacewith double quotes, bash interpreted the\as an escaped space—so your variable actually holdsNew Volume(no backslash) instead of theNew\ Volumethat's in your script. That's why sed can't find a match. - Special characters in your path are messing with sed: The
/in your paths is sed's default delimiter, so when you plug the variable into the sed command, it's breaking the syntax.
Step-by-Step Fix
1. First, Define Your Variables Correctly
Use single quotes to preserve the backslash in your path (bash won't parse escape sequences inside single quotes):
replace='/run/media/nnice/New\ Volume/FILES/Softwares/HTTP/Downloads/' replacewith='/home/nnice/Windows/D/FILES/Softwares/HTTP/Downloads/'
If you prefer double quotes, you need to escape the backslash itself (so bash stores a single backslash in the variable):
replace="/run/media/nnice/New\\ Volume/FILES/Softwares/HTTP/Downloads/" replacewith="/home/nnice/Windows/D/FILES/Softwares/HTTP/Downloads/"
2. Use a Different Delimiter in sed
Since your paths are full of /, switch to a delimiter that doesn't appear in your paths—like | (pipe). This avoids having to escape every / in your variables.
First, test the replacement without modifying the file to make sure it works:
sed "s|$replace|$replacewith|g" script.sh
If you see the correct path changes in the output, go ahead and modify the file with the -i flag:
sed -i "s|$replace|$replacewith|g" script.sh
Alternative: Escape Special Characters (For Any Delimiter)
If you ever need to use the default / delimiter, or your path contains the delimiter you chose, you can escape the special characters in your variables first:
# Escape / and & (common sed special chars) in both variables escaped_replace=$(printf '%s' "$replace" | sed 's/[\/&]/\\&/g') escaped_replacewith=$(printf '%s' "$replacewith" | sed 's/[\/&]/\\&/g') # Now run the sed command sed -i "s/$escaped_replace/$escaped_replacewith/g" script.sh
Full Working Example
Here's the complete sequence to run:
# Set variables correctly replace='/run/media/nnice/New\ Volume/FILES/Softwares/HTTP/Downloads/' replacewith='/home/nnice/Windows/D/FILES/Softwares/HTTP/Downloads/' # Preview changes sed "s|$replace|$replacewith|g" script.sh # Apply changes to the file sed -i "s|$replace|$replacewith|g" script.sh
内容的提问来源于stack exchange,提问作者Nitin Kumar

