Ubuntu – How to grep in the content of a string variable

grep

How to do a grep in a variable? I have stored the wget output in a variable and I need to extract out some strings from it.
Like the content of the variable is

upgrade http://wordpress.org/download/ http://wordpress.org/wordpress-3.0.5.zip 3.0.5 en_US 4.3 4.1.2

I need to check if the string contains the word upgrade, so I can do a simple grep and then check the exit status of it by $? and proceed.

How can I get the value 3.0.5 which is actually the fourth word?

And how to actually grep in a variable?

Best Answer

If you are just looking for a word you can use a for loop.

STRING="upgrade this if you can"
for x in $STRING; do
   echo $x
   if [ "$x" = 'upgrade' ]; then
       echo found
       y=$x
       break
   fi
done 
echo $y

If upgrade is always in the same position you could try array assignment.

declare -a z
z=($STRING)
echo ${z[0]}