80

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
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
Leo Chan
  • 4,217
  • 8
  • 31
  • 47

3 Answers3

185

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
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
24
echo $website | sed 's/\//\\\//g'

or, for better readability:

echo $website | sed 's|/|\\/|g'
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
2

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

Noam Manos
  • 15,216
  • 3
  • 86
  • 85