Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

replace - Can I use sed to manipulate a variable in bash?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...