0

I have this string stored in a variable

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

and I would like to take only the numerical values for data-severity-codes. Take in mind that:

  1. The numerical values are 1,2 or 3 characters
  2. The data-line-id length change
1

2 Answers 2

2

You can do it like this:

$ 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"

You can also use sed to remove " and replace , by a blank if you need it:

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

You can use the matching operator =~:

#! /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

Output:

4,6,9

Or use an XML-aware tool:

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .