Tuesday, February 6, 2024

[SOLVED] Possible to exclude in Bash regex?

Issue

If I have the following files

aaa-a1
aaa-a2
c
d
eee-e1

Is it then possible to write a regex for ls that lists all files except for aaa* and eee* ?

Had it been JavaScript I would have written

^/(?!aaa|eee)([a-z0-9]+)$ 

but ls ^/(?!aaa|eee)([a-z0-9]+)$ is not a valid regex in Bash.


Solution

You can do this using extended glob pattern in bash like this:

shopt -s extglob
ls !(@(aaa|eee)-*)

c      d

Here:

  • shopt -s extglob enables extended glob
  • ! is a negation
  • @(...|...) selects one of the alternatives


Answered By - anubhava
Answer Checked By - Willingham (WPSolving Volunteer)