How do you grep a variable?
It seems like this would be a common question but I could not find an answer?
I'm writing a script and I want to do a grep on a variable. In my case I'm performing a division and I want to grep the variable containing the results to see if it is a whole number. Basically I want to do something like this: grep "." $RESULT |
by habit is to do something like "echo $VAR | grep whatever" which isn't the best way, but it's what falls out of my fingers each time. Does that cover what you want?
|
This should work:
Code:
echo "$RESULT" | grep "\." |
Basically you may echo a variable and pipe the result to the grep command:
Code:
echo "$var" | grep pattern Edit: oops... too late! ;) |
Doesn't quite seem to work. Here is what I'm using to test it.
~#V=1.5; echo $V | grep "." 1.5 Which seem OK, but when I do this: ~#V=2; echo $V | grep "." 2 I would expect grep to not print anything on the second case. |
Ok it looks like I need a \ in from of my .
~ # V=2.5; echo $V | grep "\." 2.5 ~ # V=2; echo $V | grep "\." ~ # Thanks guys! |
but you know your regex's right? "." means a single character, not a period. escape it - \. or use single quotes around it, not double.
|
Quote:
|
please keep up. At least I replied too late within a minute!
|
don't need to use external tools, in bash
Code:
$ string="1.23" |
+1 for ghostdog74's suggestion of doing it in the shell without using grep. A more general test for an integer (as opposed to a decimal number with a fractional part) is
Code:
[[ "${RESULT//[0-9]/}" != '' ]] && { <whatever you want to do if RESULT is not integer>; } |
Quote:
Code:
$ shopt -s extglob |
Not as intuitive as previous answers but this should work in at least bash and ksh:
Code:
a=12.34 |
All times are GMT -5. The time now is 03:42 AM. |