我將此字串儲存在變數中
<li class="rainbow-list-item southern disrupted " data-line-id="lul-southern" data-severity-codes="4,6,9" data-mode="national-rail">
我只想獲取數據嚴重性代碼的數值。請記住:
- 數值為 1,2 或 3 個字符
- 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\"