Trouble with test pattern

I can run the following command

IFS='\n';ls |grep "02\\-[0-9]\{2\}-2015" |while read file;do cp $file /tmp/feb

However, what I really want to do is

 if [[ $file =~ "02\\-[0-9]\{2\}-2015"  ]]; then cp $file /tmp/feb;fi

The problem is the regex is not picked up in this test condition. Can someone help? In addition, I need to make sure that the newline is not printed, the filenames have spaces in them, and that is why IFS='\n' is used.

Would that work? Remove the echo if it does.

for file in *; do
    if [[ "$file" =~ 02\\-[0-9]\{2\}-2015 ]]; then
       echo cp "$file" /tmp/feb
   fi
done
1 Like

Try removing the quotes, it may be taking them literally.

I believe the following change to Aia's test should match the original grep criteria. Also =~ if for awk, in bash/ksh use = instead

for file in *; do
    if [[ "$file" = *02-[0-9][0-9]-2015* ]]
    then
       echo cp "$file" /tmp/feb
   fi
done

This is the line that the OP posted having problems with:

if [[ $file =~ "02\\-[0-9]\{2\}-2015"  ]];

The intention was to just show where the trouble originate from, thus, basically, the copy and paste.
Otherwise, I would have not even bother with a loop, a simple ls pattern | xargs cp would have done the job.

Since version 3 bash obtained its own regex-match operator: =~.

1 Like

Thanks Aia, never used the regex-match of bash, probably looked and it a while ago and ignored due to portability issues.

Yes the important details for the OP is to quote $file both in the cp command line and the test expression. Also don not escape or quote the RE:

if [[ "$file" =~ 02-[0-9]{2}-2015 ]]; then cp "$file" /tmp/feb;fi