Linux – How to use grep on a variable or string

bashgreplinux

I'm writing a bash script and I need to check if a file name has a number at the end (after a period) and if so get it, but I can't figure out how to use regex on a variable or string.

I was able to use echo in the terminal to pipe a string into grep, like this:

 echo "filename.txt.123" | egrep -o "\.[0-9]+$" | egrep -o "[0-9]+"

But I need to assign the output of this to a variable. I tried doing this:

 revNumber= echo "filename.txt.123" | egrep -o "\.[0-9]+$" | egrep -o "[0-9]+"

But that doesn't work. I tried a bunch of other things as well, but nothing was valid.

In my bash script I want to use grep on a variable and not a string, but the concept here is the same.

How can I use grep on a string or variable and then save the result into another variable?

Best Answer

To assign the output of a command to a variable, use $():

revNumber=$(echo "filename.txt.123" | egrep -o "\.[0-9]+$" | egrep -o "[0-9]+")

If all you care about is matching, you might want to consider case:

case foo in
  f*) echo starts with f
   ;;
  *) echo does not start with f
   ;;
esac
Related Question