我可以使用 sed 来操作 bash 中的变量吗?

在我的程序中,我希望首先获得用户输入,并在每个 /之前插入一个 \ 所以我写了这个,但是没有用。

echo "input a website"
read website


sed '/\//i\/' $website
119445 次浏览

Try this:

website=$(sed 's|/|\\/|g' <<< $website)

Bash actually supports this sort of replacement natively:

${parameter/pattern/string} — replace the first match of pattern with string.
${parameter//pattern/string} — replace all matches of pattern with string.

Therefore you can do:

website=${website////\\/}

Explanation:

website=${website // / / \\/}
^  ^ ^  ^
|  | |  |
|  | |  string, '\' needs to be backslashed
|  | delimiter
|  pattern
replace globally
echo $website | sed 's/\//\\\//g'

or, for better readability:

echo $website | sed 's|/|\\/|g'

You can also use Parameter-Expansion to replace sub-strings in variable. For example:

website="https://stackoverflow.com/a/58899829/658497"
echo "${website//\//\\/}"

https:\/\/stackoverflow.com\/a\/58899829\/658497