如何匹配 bash 正则表达式中的任何字符?

如何匹配 bash 正则表达式中的任何字符?

在 bash 脚本中,为什么

message='123456789'
echo "${message//[0-9]/*}"

展示*********

message='123456789'
echo "${message//./*}"

显示123456789

我看过的所有文档都说.匹配正则表达式中的任何字符,甚至在 bash 中也是如此,但对我来说不起作用。如何在 bash 中匹配任何字符?

答案1

文档中哪里提到了这.意味着任意字符 在模式匹配中?其中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.

正则表达式与 shell 模式匹配不同: https://unix.stackexchange.com/questions/439875/why-not-seeing-shell-globs-as-a-dialect-of-regex。如果您想使用 ${parameter/pattern/string}Bash 中的语法将所有字符替换为另一个字符,您需要使用?如下方法:

$ echo "${message//?/*}"
*********

您可以在使用正则表达式的程序中使用.而不是?,例如sed

$ sed 's,.,*,g' <<< "$message"
*********

相关内容