我可以使用 sed 来操作 bash 中的变量吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6744006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I use sed to manipulate a variable in bash?
提问by Leo Chan
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
回答by Eugene Yarmash
Try this:
尝试这个:
website=$(sed 's|/|\/|g' <<< $website)
Bash actually supports this sort of replacement natively:
Bash 实际上本身就支持这种替换:
${parameter/pattern/string}
— replace the first match of pattern
with string
.${parameter//pattern/string}
— replace all matches of pattern
with string
.
${parameter/pattern/string}
-取代的第一场比赛pattern
用string
。${parameter//pattern/string}
-更换所有比赛pattern
用string
。
Therefore you can do:
因此你可以这样做:
website=${website////\/}
Explanation:
解释:
website=${website // / / \/}
^ ^ ^ ^
| | | |
| | | string, '\' needs to be backslashed
| | delimiter
| pattern
replace globally
回答by Karoly Horvath
echo $website | sed 's/\//\\//g'
or, for better readability:
或者,为了更好的可读性:
echo $website | sed 's|/|\/|g'
回答by Noam Manos
You can also use Parameter-Expansionto replace sub-strings in variable. For example:
您还可以使用参数扩展来替换变量中的子字符串。例如:
website="https://stackoverflow.com/a/58899829/658497"
echo "${website//\//\/}"
https:\/\/stackoverflow.com\/a\/58899829\/658497
https:\/\/stackoverflow.com\/a\/58899829\/658497