Can I use sed to manipulate a variable in bash?

BashReplaceSed

Bash Problem Overview


In my program, I would like to first get the user input, and insert a \ before each / so I write this, but it doesn't work.

echo "input a website"
read website

sed '/\//i\/' $website

Bash Solutions


Solution 1 - Bash

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

Solution 2 - Bash

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

or, for better readability:

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

Solution 3 - Bash

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeo ChanView Question on Stackoverflow
Solution 1 - BashEugene YarmashView Answer on Stackoverflow
Solution 2 - BashKaroly HorvathView Answer on Stackoverflow
Solution 3 - BashNoam ManosView Answer on Stackoverflow