简体   繁体   English

在 bash 脚本中的变量中将 * 替换为 <

[英]Replacing * by < in a variable in bash script

I have a variable var="TAG: *** Reason:Circumvention *** SSC" I have to put this variable between double quotes otherwise it changes the *** into the files on my homedirectory我有一个变量 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

Now I want to change all * into another character (eg <) and put it into a new variable (so I don't have to put it into double quotes anymore) but it seems it replaces the whole variable by <.现在我想将所有 * 更改为另一个字符(例如 <)并将其放入一个新变量中(因此我不必再将其放入双引号中)但它似乎用 < 替换了整个变量。 How can I avoid this?我怎样才能避免这种情况?

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

To quote the bash manual under Pattern Matching引用Pattern Matching下的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.

Either escape the glob * or put it inside single quotes.转义 glob *或将其放在单引号内。

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

Or或者

newvar=${var//'*'/<}
  • The glob * will match all the character/strings from start to the end, and replace it with whatever you have in the Parameter Expansion replacement, in this case the < sign. glob *将匹配从头到尾的所有字符/字符串,并将其替换为参数扩展替换中的任何内容,在本例中为<符号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM