Reputation: 139
I created this regex:
'^CPU\s+LOAD\:\s+([0-9]{1,3})\s+Average\:\s+([0-9]{1,3}).?$'
to match and extract values from my string:
"CPU LOAD: 100 Average: 89"
but occasionally the values will not be available such as:
"CPU LOAD: Average: 89"
"CPU LOAD: 100 Average: "
"CPU LOAD: Average: "
and it will not match, but I need it as a place holder to return "" when values are not present.
So I have tried several things and I think this:
'^CPU\s+LOAD\:\s+([[0-9]{1,3}]?)\s+Average\:\s+([[0-9]{1,3}]?).?$'
should work, but it doesn't seem to be. Is this correct syntax?
This is my test code that wants to fail answer 1 I followed the link and it seems to work at the link page.
rx='^CPU\s+LOAD\:\s+(?:([0-9]{1,3})\s+)?Average:(?:\s+([0-9]{1,3}))?$'
line="CPU LOAD: 89 Average: 99"
if [[ $line =~ $rx ]]; then
printf "\n\n${BASH_REMATCH[1]} ${BASH_REMATCH[2]}\n\n"
else
printf "\n\nDidn't Match\n\n"
fi
I updated
rx='^CPU\ +LOAD\:\ +(([0-9]{1,3})\ +)?Average:(\ +([0-9]{1,3}))?$'
and "CPU LOAD: 100 Average: 89" passes
"CPU LOAD: Average: 89" passes
"CPU LOAD: 100 Average: " fails
The latest updates require me to:
printf "\n\n${BASH_REMATCH[1]} ${BASH_REMATCH[2]} ${BASH_REMATCH[3]} ${BASH_REMATCH[4]}\n\n"
To capture everything and puts either single value into
${BASH_REMATCH[1]} ${BASH_REMATCH[2]}
Thanks for Forth Bird's help. This is the final code that works for my needs.
rx='^CPU\s+LOAD:\s+(([0-9]{1,3})\s+)?Average:(\s+([0-9]{1,3}))?.?$'
Upvotes: 1
Views: 1053
Reputation: 163277
What you might do is use an optional non capturing group:
^CPU[[:blank:]]+LOAD\:[[:blank:]]+(([0-9]{1,3})[[:blank:]]+)?Average:([[:blank:]]+([0-9]{1,3}))?$
See the regex demo
You could match the space by escaping it or use [[:blank:]]
to match a whitespace or a tab.
rx='^CPU[[:blank:]]+LOAD\:[[:blank:]]+(([0-9]{1,3})[[:blank:]]+)?Average:([[:blank:]]+([0-9]{1,3}))?$'
line="CPU LOAD: 89 Average: 99"
if [[ $line =~ $rx ]]; then
printf "\n\n${BASH_REMATCH[2]} ${BASH_REMATCH[4]}\n\n"
else
printf "\n\nDidn't Match\n\n"
fi
Upvotes: 2