LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Pattern Matching (http://www.linuxquestions.org/questions/linux-newbie-8/pattern-matching-718575/)

Aveltium 04-12-2009 06:39 AM

Pattern Matching
 
Hi, I'm very new to shell scripting and I'm sorry if this question is too dumb.
If it is ok, please link me to some beginner guides for questions like this one.

I want to check if the entered string is a number and has 4 digits.

I heard that I should use "regular expression" or something like that to accomplish this task, but I don't know how to use it.

Code:

echo -n "Input: "
read x
if [ $x == ${...err i dont know what to put here} ]
then echo "Valid"
else echo "Invalid"
fi

Any help is much appreciated! :D


============================================
* Edit:

I have found the answer for my question, hope it helps anyone who would like to search for this:
Code:

echo -n "Input: " ; read x
if [ $(echo "$x" | grep -c "^[0-9]\{4\}$") -eq 1 ] ; then
    echo "Valid"
else
    echo "Invalid"
fi

And this is what I have learned while I was trying to ask for this, on another forum: http://www.unix.com/302306293-post8.html
I want to share it because I think it's nice and helpful. Please don't hate me for linking to other forums. :D

laceyj 04-12-2009 06:43 AM

Try looking here:
http://www.amk.ca/python/howto/regex/

Aveltium 04-12-2009 07:16 AM

Thanks for responding and the link! :D

I'm learning Bash shell script at the college. Is that Python the same or similar?

ghostdog74 04-12-2009 09:05 AM

if you are learning bash, then check out the bash link in my sig. Somewhere down the road while you are reading, there are examples of how to check for digits. go read it. good luck

i92guboj 04-12-2009 09:39 AM

Quote:

Originally Posted by Aveltium (Post 3506249)
I'm learning Bash shell script at the college. Is that Python the same or similar?

Bash and python have nothing to do with each other.

Bash is a shell. It's been made basically to let you enter commands. It's good when it comes to structuring batches of commands as well. And it has some advanced capabilities when compared to other simpler shells. But it's not a general purpose programming language. You can start to realize that when you need to do some advanced operation whit patterns and you have to resort to awk or sed, or when you need true arithmetic capabilities and you have to resort to bc, and so we could continue.

It lacks even data types, since for bash everything is a string. Bash is also damn slow.

Python on the contrary is a proper general purpose programming language, just like perl or C.

Aveltium 04-13-2009 12:14 AM

Thanks a lot laceyj, ghostdog74 and i92guboj! That helps a lot for newbies like me! :D


All times are GMT -5. The time now is 03:55 AM.