0

I am having a bash script that operates on multiple files but the operation shall not take place on a specific subset of files - if the filename matches ~.jpg [e.g. as in myimage~xa.jpg].

declare -a AFileList2

for sFile in *.jpg
do
   echo "Testing $sFile"
   if [ -d "$sFile" ]
   then
      echo "skipping directory $sFile"
   else
      if [ -f "$sFile" ]
      then
         if [[ "$sFile" =~ "*~*.*" ]]
         then
            echo "skipping $sFile"
         else
            echo "operating on  $sFile"
            AFileList2+=($sFile)
            ((iFilesFound++))
         fi

      fi
   fi
done
echo "Found by eval: $iFilesFound file(s)"

the crucial part of the for-loop above is the line

if [[ "$sFile" =~ "*~*.*" ]]

But it doesn't work.

I have it from an example in the pdf Advanced bash scripting guide where a demo script reads:

#!/bin/bash
variable="This is a fine mess."
echo "$variable"
if [[ "$variable" =~ "T*fin*es*" ]]
    # Regex matching with =~ operator within [[ double brackets ]].
then
   echo "match found"
   # match found
fi

But even this demo script does not work as expected.

any help apreciated

Cyrus
  • 84,225
  • 14
  • 89
  • 153
hy-soft
  • 163
  • 2
  • 12
  • Rather than nested ifs, please consider using `continue` to skip a file. – William Pursell Mar 08 '15 at 13:10
  • @William Pursell: Why? Could you explain (or link to an explanation) please. – hy-soft Mar 08 '15 at 16:56
  • 1
    The nested if/else hinders readability. (Also, note that your code fails to deal with files that are not directories or regular files. Why not just do `! test -f $file && continue` rather than checking that something is a directory? – William Pursell Mar 08 '15 at 20:57
  • @William Pursell: Thanks. IMHO readability is a matter of tast and a Pascal-Developer got probably a different code-set in mind than a C-programmer. The rest is an helpful advice. Thanks for that. – hy-soft Mar 08 '15 at 21:06

1 Answers1

1

Replace this (globbing?)

[[ "$sFile" =~ "*~*.*" ]]

by this Regex

[[ "$sFile" =~ .*~.*\..* ]]
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • 1
    Thanks @Cyrus. Stupid me - I have to use "real" regular expressions instead of some fileglobbing that works on command line as in ls * ~ * .jpg To make the example from ABG work I had to remove the quotes and insert dots as well. Thanks. – hy-soft Mar 08 '15 at 13:14