Regex with spaces

I have a number of files that I need to return a yes for this command.

CDATE="Feb"
 if [[ "$file" =~ [A-Z[:blank:]] && $CDATE="Feb" ]]; then echo "yes";fi

However, the files look like this:

CAR LIST DIRECTORY.TXT
CHRYSLER LIST DIRECTORY.TXT

Apparently the files are not picked up because of spaces. Can someone help? The first word only is picked up. It appears that if I do this:

file='CAR LIST DIRECTORY.TXT'

echo $file returns the correct string but I don't know how to make the regex see the string correctly. How would I be able to send a list of files with the space pattern to a variable?

Wouldn't it be helpful if you posted your OS and shell versions? Above smells like bash , but this assumption can be wrong.
How is your file variable defined? In a for loop (which would explain the cited behaviour)? With a read ?

BTW, you don't have problems with a "regex with spaces", but with spaces in variables / data that are incorrectly interpreted.

In addition:

$CDATE="Feb"

should be:

$CDATE == "Feb"

I do not think so. One of the differences between [ and [[ is that [[ is a shell-built-in replacement for test and field splitting is not done inside it. To see the difference try

cd /tmp
mkdir "test dir"
DIR="test dir"
if [ -d $DIR ] ; then echo test1: $DIR exists ; fi
if [[ -d $DIR ]] ; then echo test2: $DIR exists ; fi

You will notice that one produces a syntax error because of the unquoted blank and the other works fine - because field splitting at blanks is not done.

But there is another problem:

[[ "$file" =~ [A-Z[:blank:]] ... ]]

The quotes will make sure the regexp never matches, because they are retained. Try:

[[ $file =~ [A-Z[:blank:]] ... ]]

And also the && is not the correct AND-operator for test , it is used only in the shell! So either you couple two test-statements via a shell-AND:

if [[ "$file" =~ [A-Z[:blank:]] ]] && [[ $CDATE == Feb ]] ; then

or you do it inside test with the test-internal operator:

if [[ "$file" =~ [A-Z[:blank:]] -a $CDATE == Feb ]] ; then

I hope this helps.

bakunin

To put a fine point on it: Every modern shell has [ / test as a shell builtin (utility) and since it is still a utility, variables are expanded and field splitted so that they can be passed as fields to the utility.

[[ on the other hand, is a conditional expression which is part of the shell syntax and therefore no field splitting is performed (similar to what happens to variables in a case statement, which is also shell syntax)

---
On another note: RudiC was not referring to field splitting in the conditional expression, but the possibility that the variable does not contain the full filename and that that may be due to the way the filename was passed to the variable:

1 Like

Actually, the test looks if there's just any single upper case char OR any whitespace in the variable's contents; so both examples should print yes , as does a a string or a 1234S2345 . You may want to reconsider your problem.