CJ *_*nis 4 bash scripts regex
在 bash 脚本中,为什么
message='123456789'
echo "${message//[0-9]/*}"
Run Code Online (Sandbox Code Playgroud)
展示*********
但
message='123456789'
echo "${message//./*}"
Run Code Online (Sandbox Code Playgroud)
显示123456789?
我见过的所有文档都说.匹配正则表达式中的任何字符,甚至在 bash 中,但它对我不起作用。如何匹配 bash 中的任意字符?
文档中哪里说这.意味着
模式匹配中的任何字符?其中man 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
subdirectories.
? Matches any single character.
Run Code Online (Sandbox Code Playgroud)
正则表达式与 shell 模式匹配不同:
https://unix.stackexchange.com/questions/439875/why-not-seeing-shell-globs-as-a-dialect-of-regex。如果你想使用
${parameter/pattern/string}Bash 中的语法将所有字符替换为另一个字符,你需要?这样使用:
$ echo "${message//?/*}"
*********
Run Code Online (Sandbox Code Playgroud)
您可以在使用正则表达式的程序中使用.而不是,?例如sed:
$ sed 's,.,*,g' <<< "$message"
*********
Run Code Online (Sandbox Code Playgroud)