I’m looking to fetch a value after a match in a string.
Lets say I have two string:
string1="Name: John Doe Age: 28 City: Oklahoma City"
string2="Name: Jane Age: 29 Years City: Boston"
Now I want to set three parameters: Name, Age and City.
If I were to do:
name=$(echo "$string1" | awk '{ print $2 $3 }')
city=$(echo "$string1" | awk '{ print $5 }')
city=$(echo "$string1" | awk '{ print $8 $9 }
It would work for string1, but obviously not for string2.
After some googling I believe I should put it in some kind of array, but I do not really know how to proceed.
Basically, I want everything after Name: and before Age: to be parameter $name. Everything between Age: and City: to be $age, and so on.
Best regards
Needs bash version 3 or higher:
You might need
Age:\ ([0-9]*).*\ City:if you do not want “Years” to be included in$years.