如何在 shell 脚本中使用正则表达式从 URL 中提取字符串字段值?

How to extract string field value from a URL using regular expression in shell script?

我正在做一个项目,我需要从 bash shell 脚本对我的一台服务器进行 url 调用..

http://hostname.domain.com:8080/beat

点击上面的 url 之后,我将得到下面的响应,我需要对其进行解析并从中提取 state 的值

num_retries_allowed: 3 count: 30 count_behind: 100 state: POST_INIT num_rounds: 60 hour_col: 2 day_col: 0

现在我想使用正则表达式提取 state 变量值。我能够从中提取 countcount_behind 值,但不确定如何从中提取 state 值。

#send the request, put response in variable
DATA=$(wget -O - -q -t 1 http://hostname.domain.com:8080/beat)

#grep $DATA for count and count_behind
COUNT=$(echo $DATA | grep -oE 'count: [0-9]+' | awk '{print }')
COUNT_BEHIND=$(echo $DATA | grep -oE 'count_behind: [0-9]+' | awk '{print }')

# how to extract state variable value here?
STATE= what do I add here?

此外,如果在 $DATA 中,如果 state 变量不存在,那么我想将 0 分配给 STATE 变量。之后我想验证条件并根据它退出脚本。

如果STATE等于POST_INIT则成功退出shell脚本或STATE等于0则成功退出。

#verify conditionals
if [[ $STATE -eq "POST_INIT" || $STATE -eq "0" ]]; then exit 0; fi

你可以使用这个grep -P:

state=$(grep -oP 'state: \K\S+' <<< "$DATA")   
[[ -z "$state" ]] && state=0
echo "$state"
POST_INIT