我有一个变量var =“ TAG:***原因:绕行*** SSC” 我必须将此变量放在双引号之间,否则它将***更改为我的主目录中的文件
$ var="TAG: *** Reason:Circumvention *** SSC"
$ echo $var
TAG: sqlnet.log test.sh tst.sh Reason:Circumvention sqlnet.log test.sh tst.sh SSC
$ echo "$var"
TAG: *** Reason:Circumvention *** SSC
现在,我想将所有*更改为另一个字符(例如<),并将其放入新变量中(这样我就不必再将其放在双引号中了),但似乎它将整个变量替换为<。如何避免这种情况?
$ echo "$var"
TAG: *** Reason:Circumvention *** SSC
$ newvar="${var//*/<}"
$ echo $newvar
<
答案 0 :(得分:3)
引用bash
下的Pattern Matching
手册
模式匹配
Any character that appears in a pattern, other than the special pattern characters described below, matches itself. The NUL character may not occur in a pattern. A backslash
escapes the following character; the escaping backslash is discarded when matching. The special pattern characters must be quoted if they are to be matched literally.
The special pattern characters have the following meanings:
* Matches any string, including the null string. When the globstar shell option is enabled, and * is used in a pathname expansion context, two adjacent *s used as a
single pattern will match all files and zero or more directories and subdirectories. If followed by a /, two adjacent *s will match only directories and subdirec-
tories.
可以转义*
或将其放在单引号中。
var="TAG: *** Reason:Circumvention *** SSC"
newvar=${var//\*/<}
echo "$newvar"
或
newvar=${var//'*'/<}
*
将从头到尾匹配所有字符/字符串,并用参数扩展替换中的所有字符/字符串替换,在这种情况下为<
符号。