当变量以特殊字符开头时,用bash中的变量替换字符串 [英] Replacing string with variable in bash when variable starts with special characters

查看:45
本文介绍了当变量以特殊字符开头时,用bash中的变量替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 sed 通过用双引号()而不是单引号(')括住搜索表达式来替换变量内容的字符串是有据可查的.

Replacing a string with the contents of a variable using sed by enclosing the search expression with double (") instead of single (') quotes is well documented.

$ astring="Liftoff in [sec]"
$ for s in 3 2 1; do echo $astring | sed -e "s/\[sec\]/$s/"; done
Liftoff in 3
Liftoff in 2
Liftoff in 1

但是,如果变量内容以特殊字符开头,该如何进行上述替换?例如,变量内容可以以句点正斜杠(./)开头,如果将本地文件路径作为变量传递,通常会是这种情况?

However, how do I conduct the above replacement if the variable content starts with special characters? For example, the variable contents could start with a period forwardslash (./), which is often the case if local file paths are passed as variables?

for s in ./3 ./2 ./1; do echo $astring | sed -e "s/\[sec\]/$s/"; done
sed: -e expression #1, char 14: unknown option to `s'
sed: -e expression #1, char 14: unknown option to `s'
sed: -e expression #1, char 14: unknown option to `s'

推荐答案

您只需要使用另一个定界符:

You just have to use another delimiter :

for s in ./3 ./2 ./1; do echo "$s" | sed -e "s|\[sec\]|$s|"; done

避免与您的输入冲突

这篇关于当变量以特殊字符开头时,用bash中的变量替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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