首页 > 解决方案 > 在bash脚本的变量中用<替换*

问题描述

我有一个变量 var="TAG: *** Reason:Circumvention *** 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
<

标签: bashreplacecharacter

解决方案


引用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.

要么逃避 glob *,要么把它放在单引号内。

var="TAG: *** Reason:Circumvention *** SSC"
newvar=${var//\*/<}          
echo "$newvar"

或者

newvar=${var//'*'/<}
  • glob*将匹配从头到尾的所有字符/字符串,并将其替换为参数扩展替换中的任何内容,在本例中为<符号。

推荐阅读