Bash脚本中的正则表达式匹配行尾$无法工作

7

我正在尝试在bash脚本中使用简单的正则表达式语句,以匹配并替换单词的结尾。以下是我尝试做的事情。

wordh > word:’

以下是我正在使用的代码。
#!/bin/bash
STAT=${STAT/h$/:’}

我不太熟悉bash脚本,但是我认为它与$有关,因为它被用来标记变量。我尝试了转义它以及在它之后添加另一个/。当我移除$时,它可以正常工作(但无法检查单词的结尾)。

2个回答

4
正则表达式有一点不同。尝试使用以下内容:
STAT=${STAT/%h/:’}

来自 man 手册:

${parameter/pattern/string}

.         The pattern is expanded to produce a pattern just as in pathname
          expansion.   Parameter is expanded and the longest match of pat-
          tern against its value is replaced  with  string.   If  Ipattern
          begins  with /, all matches of pattern are replaced with string.
          Normally only the first match is replaced.   If  pattern  begins
          with  #, it must match at the beginning of the expanded value of
          parameter.  If pattern begins with %, it must match at  the  end
          of  the expanded value of parameter.  If string is null, matches
          of pattern are deleted and the / following pattern may be  omit-
          ted.   If  parameter  is  @  or *, the substitution operation is
          applied to each positional parameter in turn, and the  expansion
          is  the  resultant list.  If parameter is an array variable sub-
          scripted with @ or *, the substitution operation is  applied  to
          each  member  of  the  array  in  turn, and the expansion is the
          resultant list.

3
更确切地说,这根本不是一个正则表达式。 - tripleee
如果启用了extglob,则它是一个正则表达式,但默认情况下它不是。 - that other guy

0

$ 不是单词的一部分

你可以尝试

    STAT=wordh\$

尝试一下

     STAT=${STAT/h$/:’}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接