I have a shell script in tcsh to which I pass an argument, the length of which can vary. The possible values of the argument are the letters -c,s,i,q,a. and also a combination of these letters. (e.g: cs,si,ca,iq,qa,csq,acs,csia ..etc). The order of the letters does not matter. My problem is to check the argument for any character other than these 5 and if any of the valid character appear more than one time (zero time is ok). The script should check both the conditions and throw an error. Is there any regular expression that I can use with if statement for this purpose?
Asked
Active
Viewed 2.3k times
-2
-
Please post your code. – Feb 12 '13 at 16:41
-
2[What have you tried?](http://whathaveyoutried.com/) – ruakh Feb 12 '13 at 16:55
-
I call the script as "myscript -csq". I tried a code like below. if ("$1" =~ [csqai]) echo "Valid argument" else echo "Invalid" endif But this code does not throw error if two c's are there. – user2065523 Feb 12 '13 at 17:00
-
I missed a 'then' when I posted. It is if ("$1" =~ [csqai]) then echo "Valid argument" else echo "Invalid" endif – user2065523 Feb 12 '13 at 17:02
-
1Edit the code *into your question*, so others can find it more easily and so you can format it properly. – Keith Thompson Feb 13 '13 at 23:15
-
1tcsh's `=~` operator doesn't work on regular expressions. The right operand is a "glob-pattern"; `man tcsh` for details. If you really need regular expressions, take a look at the `expr` command. And the obligatory link: http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/ – Keith Thompson Feb 13 '13 at 23:16
2 Answers
3
Here is a sample piece of code you can use. The use of an "X" is to force the comparison to be a string.
#!/bin/csh -f
if ( $#argv > 0 ) then
echo arg is $1
if ( X$1 =~ X-* ) then
echo "we have an argument"
if ( "X$1" =~ X-c[aeiou] ) then
echo I found -c followed by vowel
else if ( "X$1" =~ "X-c" ) then
echo I found -c alone
else
echo I found a -c but not a valid combo
endif
else
echo I found an unknown argument: $1
endif
endif

Bruce Barnett
- 904
- 5
- 11
0
This will be easiest to do with two regex checks, one for validity of all letters and another to look for duplicate letters.
Take a look at this code:
#!/bin/tcsh
echo $1 | grep -q -e "[^csqai]"
if ( $? != 0 ) then
echo "Valid characters"
else
echo "Invalid characters"
endif
echo $1 | grep -q -e "\([csqai]\).*\1"
if ( $? != 0 ) then
echo "No repeated valid characters"
else
echo "Repeated valid characters"
endif
The first regex looks for all characters which are not valid and the second looks for any repeated characters
I don't know how to do these checks in tcsh
, so I did them with grep
. The -q
flag makes grep
silent. $?
is 0 if no match is found.

Sudo Bash
- 373
- 5
- 14
-
when I tried, the posted code does not catch if the argument is something like cqm where an illegal character comes after one or more legal characters. – user2065523 Feb 13 '13 at 06:55