我可以使用sed在bash中操作变量吗? [英] Can I use sed to manipulate a variable in bash?

查看:88
本文介绍了我可以使用sed在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

推荐答案

尝试一下:

website=$(sed 's|/|\\/|g' <<< $website)

Bash实际上支持:

Bash actually supports this sort of replacement natively:

${parameter/pattern/string} —将pattern的第一个匹配项替换为string.
${parameter//pattern/string} —将pattern的所有匹配项替换为string.

${parameter/pattern/string} — replace the first match of pattern with string.
${parameter//pattern/string} — replace all matches of pattern with string.

因此,您可以这样做:

website=${website////\\/}

说明:

website=${website // / / \\/}
                  ^  ^ ^  ^
                  |  | |  |
                  |  | |  string, '\' needs to be backslashed
                  |  | delimiter
                  |  pattern
                  replace globally

这篇关于我可以使用sed在bash中操作变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆