-2

I'm very new to Bash. Can someone tell me what am I doing wrong. I tried the following regex pattern online and it works fine. But Bash script below refuses to match.

I need to extract the value of status: from the last line of a text block like so:

res=$(cat <<-EOM
Conducting pre-submission checks for my.zip and initiating connection to the Apple notary service...
Submission ID received
  id: 573ebf8c-5434-4820-86c6-46adf01f81a9
Successfully uploaded file
  id: 573ebf8c-5434-4820-86c6-46adf01f81a9
  path: path-to.zip
Waiting for processing to complete.
Current status: Invalid.....Processing complete
  id: 573ebf8c-5434-4820-86c6-46adf01f81a9
  status: Invalid
EOM
)

# Get status -- need word "invalid" from this line:  status: Invalid
status=""
regex='status:\s*(\w+)$'
[[ $res =~ $regex ]] &&
  status=${BASH_REMATCH[1]}

echo "stat=$status"
c00000fd
  • 20,994
  • 29
  • 177
  • 400

1 Answers1

1

warning the PCRE like syntax \w is not supported in your version of bash.

What I would do:

#!/usr/bin/env bash

# let's KISS: Keep It Simple Stupid
res='
Conducting pre-submission checks for my.zip and initiating connection to the Apple notary service...
Submission ID received
  id: 573ebf8c-5434-4820-86c6-46adf01f81a9
Successfully uploaded file
  id: 573ebf8c-5434-4820-86c6-46adf01f81a9
  path: path-to.zip
Waiting for processing to complete.
Current status: Invalid.....Processing complete
  id: 573ebf8c-5434-4820-86c6-46adf01f81a9
  status: Invalid
'

# Get status -- need this one:  status: Invalid
status=""
regex='status:[[:space:]]*([[:word:]]+)'
[[ $res =~ $regex ]] && status=${BASH_REMATCH[1]}

echo "stat=$status"

Output

stat=Invalid

The regular expression matches as follows:

Node Explanation
status: 'status:'
[[:space:]]* any character of: whitespace characters (like \s) (0 or more times (matching the most amount possible))
( group and capture to \1:
[[:word:]]+ any character of: alphanumeric and underscore characters (like \w) (1 or more times (matching the most amount possible))
) end of \1

For some doc about POSIX character classes, see POSIX spec's

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223