I have a string which can contain 2 or more integers. I am trying to extract only the 2nd integer but the following code is printing all occurences.
#!/bin/bash
TEST_STRING=$(echo "207 - 11 (INTERRUPT_NAME) 0xffffffff:0xffffffff")
ERROR_COUNT=$(echo $TEST_STRING | grep -o -E '[0-9]+')
echo $ERROR_COUNT
The output is:
207 11 0 0
Basically I would like ERROR_COUNT to be 11 for the given TEST_STRING.
Using bash's =~
operator:
$ test_string="207 - 11 (INTERRUPT_NAME) 0xffffffff:0xffffffff"
$ [[ $test_string =~ [0-9]+[^0-9]+([0-9]+) ]] && [[ ! -z ${BASH_REMATCH[1]} ]] && echo ${BASH_REMATCH[1]}
11
Explained:
[[ $test_string =~ [0-9]+[^0-9]+([0-9]+) ]]
if $test_string
has substring${BASH_REMATCH[1]}
&&
and[[ ! -z ${BASH_REMATCH[1]} ]]
something is actually set to the variable&&
"then" echo ${BASH_REMATCH[1]}
output the variable#!/bin/bash
TEST_STRING=$(echo "207 - 11 (INTERRUPT_NAME) 0xffffffff:0xffffffff")
ERROR_COUNT="$( echo "${TEST_STRING}" | awk '{print $3}' )"
echo "${ERROR_COUNT}"
The output is:
11
Here is my take on it, using read
to parse the separate variables:
TEST_STRING="207 - 11 (INTERRUPT_NAME) 0xffffffff:0xffffffff"
read num sep ERROR_COUNT rest <<<"$TEST_STRING"
echo ${ERROR_COUNT}
11
Using an auxiliary variable:
TEST_STRING="207 - 11 (INTERRUPT_NAME) 0xffffffff:0xffffffff"
# Remove everything until the space in front of the 11
temp=${TEST_STRING#*- }
# Remove what comes afterwards
ERROR_COUNT=${temp%% *}
This assumes that the error count is preceded by -
followed and one space, and is followed by a space.
User contributions licensed under CC BY-SA 3.0