Bash: extract 2nd integer from test string

0

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.

regex
bash
shell
grep
asked on Stack Overflow Apr 21, 2020 by user1397215

4 Answers

1

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
    integer — non-integer — integer, the latter integer is set to variable ${BASH_REMATCH[1]}
  • && and
  • [[ ! -z ${BASH_REMATCH[1]} ]] something is actually set to the variable
  • && "then"
  • echo ${BASH_REMATCH[1]} output the variable
answered on Stack Overflow Apr 21, 2020 by James Brown
0
#!/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
answered on Stack Overflow Apr 21, 2020 by keithpjolley
0

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
answered on Stack Overflow Apr 21, 2020 by Eric Bolinger
0

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.

answered on Stack Overflow Apr 21, 2020 by user1934428

User contributions licensed under CC BY-SA 3.0