Search code examples
bashfor-loopglobinverse-match

bash 4.1.2(2): how to apply regex inverse matching in a for-loop?


I want to loop through only the directories that do NOT contain string "unicredit". Given this directory list (located in /tmp/scripts/bash/test/):

par_q
swx_i
swx_r
unicreditucispa_ams_b
unicreditucispa_ams_m
unicreditucispa_ber_b

I launched the following one-liner:

for i in /tmp/scripts/bash/test/^((?!unicredit*).)*$; do echo FOUND $i; done

And expected the following output:

FOUND par_q
FOUND swx_i
FOUND swx_r

But instead got this error:

-bash: syntax error near unexpected token `('

I attempted to escape some/all parentheses with \ and also tried to enclose the regex with quotes, but it did not solve the problem.

What amendments should I do in order to get the output that I desire?

Thank you.


Solution

  • I suggest:

    shopt -s extglob # enable extglob
    for i in /tmp/scripts/bash/test/!(*unicredit*); do echo "FOUND $i"; done