Register
It is currently Mon Sep 01, 2014 1:37 am

Problems with regular expressions


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Sat Mar 27, 2010 2:39 am   

Joined: Sat Mar 27, 2010 2:26 am
Posts: 2
Hi, I'v just started learning about bash scripting, however I already have a problem. I'm trying to use regular expressions to validate user input and if it's correct, than put it into my file:

Code:
if echo "$INI $LIM $STI $VEC $NMD $MSU" | grep -q -i ^[B-Z]+[[:space:]][a-z][[:space:]][a-z][[:space:]][a-z][[:space:]][a-z][[:space:]][a-z]$; then
      echo -e "$INI $LIM $STI $VEC $NMD $MSU\t" >> $FILE


The problem is - if I have a line like "a a a a a a" (where the first letter logically isn't right) it says, that everything's fine and writes the output to the file - I don't understand it. As I understood, it should be checking if the first character is from capital 'B' to capital 'Z' and find at least one match. Perhaps I'm not doing it correctly (I didn't change the rest of REs, just the first variable, cause obviously there's no point if even the first doesn't work). What I'm trying to achieve is this output form (I'll explain it in example):

Somename Somesurname Style 18 16.08.2007 23.45

Hope, you can help me.


Top
 Profile  
 PostPosted: Sat Mar 27, 2010 5:09 am   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 535
hi nowbert,
removing the + helps
Code:
[[ "a a a a a a" =~ ^[B-Z][[:space:]][a-z][[:space:]][a-z][[:space:]][a-z][[:space:]][a-z][[:space:]][a-z]$ ]] && echo ok || echo KO
KO

[[ "c a a a a a" =~ ^[B-Z][[:space:]][a-z][[:space:]][a-z][[:space:]][a-z][[:space:]][a-z][[:space:]][a-z]$ ]] && echo ok || echo KO
KO

[[ "C a a a a a" =~ ^[B-Z][[:space:]][a-z][[:space:]][a-z][[:space:]][a-z][[:space:]][a-z][[:space:]][a-z]$ ]] && echo ok || echo KO
ok
and as you see, no need of grep.
[[ is kinda of improved [ (a synonym for the `test' builtin), which supports regexps

btw, this could be shortened to
Code:
[[ "C a a a a a" =~ ^([B-Z] [a-z] [a-z] [a-z] [a-z] [a-z])$ ]] && echo ok || echo KO
ok
note parenthesis


Top
 Profile  
 PostPosted: Sat Mar 27, 2010 6:33 am   

Joined: Sat Mar 27, 2010 2:26 am
Posts: 2
Wow, it works - thanks for the quick response and valuable help, problem solved :)


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 10 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP