BASH 从字符串中获取值

BASH 从字符串中获取值

我将此字符串存储在变量中

<li class="rainbow-list-item southern disrupted " data-line-id="lul-southern" data-severity-codes="4,6,9" data-mode="national-rail">

我只想获取数据严重性代码的数值。请记住:

  1. 数值为 1,2 或 3 个字符
  2. data-line-id 长度变化

答案1

你可以这样做:

$ MYVAR='<li class="rainbow-list-item southern disrupted " data-line-id="lul-southern" data-severity-codes="4,6,9" data-mode="national-rail">'
$ echo $MYVAR | tr ' ' '\n' | awk -F= '/data-severity-codes/ {print $2}'
"4,6,9"

如果需要,您还可以使用 sed 删除 " 并将 , 替换为空白:

$ echo $MYVAR | tr ' ' '\n' | awk -F= '/data-severity-codes/ {print $2}' | sed -e 's/"//g' -e 's/,/ /g'
4 6 9

答案2

您可以使用匹配运算符=~

#! /bin/bash
var='<li class="rainbow-list-item southern disrupted " data-line-id="lul-southern" data-severity-codes="4,6,9" data-mode="national-rail">'

if [[ $var =~ data-severity-codes=\"([^\"]+)\" ]] ; then
    echo ${BASH_REMATCH[1]}
fi

输出:

4,6,9

或者使用 XML 感知工具:

xmllint --xpath li/@data-severity-codes - <<< "$var</li>" \
| cut -f2 -d\"

相关内容