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.

1
  • try '[0-9]{2}' Commented Apr 21, 2020 at 2:19

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.