You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用sed命令替换变量中存储的文件路径

Fixing Your sed Path Replacement Issue

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:

  1. Your variable isn't storing the right path: When you defined replace with double quotes, bash interpreted the \ as an escaped space—so your variable actually holds New Volume (no backslash) instead of the New\ Volume that's in your script. That's why sed can't find a match.
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 14:37:29