The code given below does this. But its ugly and is very dependant on external calls.
I reviewed Chris FA Johnsons site / link Extracting parts of a string by Chris F.A. Johnson and reviewed a few books I have written by him and looked at web resources and dont find a good method to execute the same without external calls.
Is there anyway I can isolate these pieces of information without external calls ?
string="SNMPv2-MIB::sysObjectID.0 = OID: SNMPv2-SMI::enterprises.9.1.1745"
regex1="sysObjectID"
regex2="[0-9]{4}$"
if [[ "$string" =~ $regex1 ]] then
[[ "$string" =~ $regex2 ]] then
echo "matched part is ${BASH_REMATCH[1]}"
fi
fi
As general note - some bash regex strings fail when used directly on the command line. Spaces in regex are an example.
It is probably best practice to make them variables: bash - Capturing Groups From a Grep RegEx - Stack Overflow
Dennis Williamson's answer comment section
If I see many if [[ $var in a row then it's time to think of a case-esac.
But it uses a whole line glob match, not a regular expression.
Here a leading and trailing * allow preceding and succeeding characters (while a regular expression does not need leading/trailing .* )
while read line
do
case $line in
(*sysName*) sysN=${line##* } ;;
(*sysObjectID*) sysO=${line##*.} ;;
(*sysDescr*) TMP=${line##*Version }; sysD=${TMP%% RELEASE*} ;;
esac
done < <($SNMPG $RW -v2c -mALL $i sysDescr.0 sysName.0 sysObjectID.0 2>/dev/null)
printf "%s,%s,%s\n" "$sysN" "$sysD" "$sysO"
I also replaced the "herestring made of a command substitution" <<< $( ) by a "process substitution" < <( ) .