Regex matching end of a line $ not working in Bash Script
Asked Answered
E

2

7

I'm trying to do a simple regex statement in a bash script that will match and substitute the end of a word. Below is what I'm trying to do.

wordh > word:’

Below is the code I'm using.

#!/bin/bash
STAT=${STAT/h$/:’}

I'm not familiar with bash scripting and I'm thinking it has something to do with the $ because it's used to mark a variable. I've tried to escape it as well as adding another / after it. When I remove the $ it works (without checking the end of a word).

Energetic answered 9/1, 2016 at 6:24 Comment(0)
R
4

The regex's there are a little different. Try:

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

From the man page:

${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.
Redbreast answered 9/1, 2016 at 6:34 Comment(2)
More like, it's not a regex at all.Acerbity
It's a regex if extglob is enabled, but by default it's not.Blondellblondelle
L
0

$ is not part of the word

you can try

    STAT=wordh\$

than try

     STAT=${STAT/h$/:’}
Laclos answered 9/1, 2016 at 6:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.