Search code examples
regexbashstringstring-parsing

How Do I Pull Info from String


I am trying to pull dynamics from a load that I run using bash. I have gotten to a point where I get the string I want, now from this I want to pull certain information that can vary. The string that gets returned is as follows:

Records: 2910 Deleted: 0 Skipped: 0 Warnings: 0

Each of the number can and will vary in length, but the overall structure will remain the same. What I want to do is be able to get these numbers and load them into some bash variables ie:

RECORDS=??
DELETED=??
SKIPPED=??
WARNING=??

In regex I would do it like this:

Records: (\d*?) Deleted: (\d*?) Skipped (\d*?) Warnings (\d*?)

and use the 4 groups in my variables.


Solution

  • You can use regex matching in Bash versions >= 3.2:

    [[ $line =~ ([[:digit:]]+).*([[:digit:]]+).*([[:digit:]]+).*([[:digit:]]+) ]]
    
    RECORDS=${BASH_REMATCH[1]}
    DELETED=${BASH_REMATCH[2]}
    SKIPPED=${BASH_REMATCH[3]}
    WARNING=${BASH_REMATCH[4]}