Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with grep and regular expresions

Status
Not open for further replies.

ojosVerdes

Technical User
Oct 10, 2002
50
US
I have the following function that should work if you enter any of the follwing paterns:

+8 -9
-9 8
9 9
-9 -8
+9 +8
0 0

I have tested it successfully with
-9 8
9 9
-9 -9
0 0

The only thing that does not accept is the + sing infront of the number.

Can anybody please help.


checkinput()
{
echo $1 | grep -Eq '^(\+|-)?[0-9]+$'
return $?
}
 
Your regular expression is unbalanced and does not work as written here. So, I believe what you tried to write says:
at the beginning of the line match 0 or 1 + or - sign
followed by 1 or more digits until the end of line.

If you use something like this:
grep -E '^[+|-]?[0-9]+$'

it will match from beginning of line zero or 1 of the symbols in the character class containing "+" and "-". (You do not have to escape the + or the - if you put it in a character class.) Followed by 1 or more digits until the end of line. This will only match lines that have one number on the line.

If you want to match lines with more than one number delimited by spaces (not tabs) then you'll want to use something like this:
grep -E '([+|-]?[0-9]+ *)+$'

Note the space after "[0-9]+"
Note that I removed the ^
Note the ()'s around the expression so that it will be matched repeatedly one or more times until the end of the line.

Hope that helps ... let me know if you got what you needed.
 
Thanks for the reply.

However I am still having the same problem with number that have a leading + sing. for example if I enter +4 +7 it complains that "expr: non-numeric argument".
Here is the script:

#!/bin/sh
checkinput()
{
echo $1 | grep -E '([+|-]?[0-9]+ *)+$'
return $?
}

exitusage()
{
echo "Usage: Proj4 Integer1 Integer2"
exit
}

[ $# -ne 2 ] && exitusage
checkinput $1 || exitusage && A=$1
checkinput $2 || exitusage && B=$2
echo $A
echo $B

when I call the script as follow:
proj4 +6 +5

I get an error.

 
I got it.
My mistake.
I apologize, it was warking all the way. I had -Eq instead of just -E and I was not seeing it.

Thanks

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top