0

I'm using this as script in Mac automator to do something according to file extension :

if [[ $f =~ .*\.(pdf|doc|docx|rtf) ]]
then ........

BUT if there is pdf or doc or docx or rtf anywhere in file name, not only as extension after dot (.), it's works ?!? it's getting TRUE and going to "then" to execute whatever I wrote there... file with name "my txt file.ddd" is TRUE for this question!

Why is it happen ???

When I run this script in some online bash shell and doing f="my txt file.ddd" it's getting FALSE, as I expect.

What am I doing wrong ? What

if [[ $f =~ .*\.(pdf|doc|docx|rtf) ]]
then ........

is actually doing ? WHERE IS IF SEARCHING FOR MY STRING Thanks.

aynber
  • 22,380
  • 8
  • 50
  • 63
Gerti
  • 1
  • 1
  • This has nothing to do with `if`, this is all about `[[` – William Pursell Oct 08 '22 at 11:52
  • @WilliamPursell yes, I know that it's all about the [[ and the symbols .*\. ? What the .*\. doing with the string ? – Gerti Oct 08 '22 at 12:13
  • regex searches generally look for substring matches (i.e. does this pattern appear *somewhere in* the string) rather than whole-string matches. That's why regex has "anchors": `^` matches the beginning of the string, and `$` matches the end, so you can force whole-string (or beginning or end) if you want. See [this question](https://stackoverflow.com/questions/3333598/double-anchoring-regular-expressions) for example. – Gordon Davisson Oct 08 '22 at 15:28
  • 1
    A correct way to check the extension would be `[[ $f =~ \.(pdf|docx?|rtf)$ ]]` – Fravadona Oct 08 '22 at 18:32
  • @Fravadona Thanks. But what the "$" do at the end of this expression? – Gerti Oct 09 '22 at 07:52
  • It’s an anchor that means end-of-string in a bash regex – Fravadona Oct 09 '22 at 08:42

1 Answers1

0

The =~ operator is the regexp matching You can try to simplify it to something like $f =~ "\.(pdf|doc|docx|rtf)$" Or you can follow some answers from here

Anton
  • 101
  • 1
  • 8