bash - 在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
<
解决方案
引用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
*
将匹配从头到尾的所有字符/字符串,并将其替换为参数扩展替换中的任何内容,在本例中为<
符号。
推荐阅读
- python - 有没有办法用熊猫中的另一个移位列减去一列的值?
- python - JupyterRendered 不显示形状
- node.js - 在 Express 中发现 404 错误时添加失败页面
- node.js - Node js中的角色和权限不起作用
- ethereum - 在持有者之间划分合约价值(实际上是代币合约)
- python - 将无向图转换为 CNF SAT 以进行 3 着色
- jquery - 在 React 中更改具有危险设置的 innerhtml 父属性的孩子的图像源属性
- javascript - 在三元中使用 typeof
- python - 迭代具有不同字段的嵌套字典列表
- java - 弹性搜索 - 无法初始化 SSL - 证书问题