Can I use sed to manipulate a variable in bash?

后端 未结 3 942
野的像风
野的像风 2020-12-02 08:55

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          


        
相关标签:
3条回答
  • 2020-12-02 09:39
    echo $website | sed 's/\//\\\//g'
    

    or, for better readability:

    echo $website | sed 's|/|\\/|g'
    
    0 讨论(0)
  • 2020-12-02 09:48

    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

    0 讨论(0)
  • 2020-12-02 09:52

    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
    
    0 讨论(0)
提交回复
热议问题