Bash – List files that match a pattern but ignore files that match another pattern

bashlinuxlspatterns

Let's say I have a directory with files a1, a2, a3, b1, b2, b3. I only want to match files that start with a but don't contain 3. I tried ls -I "*3" *a* but it returns a1 a2 a3, even though I don't want it to match a3. Is this possible with ls?

Best Answer

Just:

shopt -s extglob  
ls a!(*3*)
  • shopt -s extglob activates extended globbing.
  • a matches the starting a
  • !() negates the match inside the ()...
    • *3* which is 3 and anything before or after it.

$ touch 1 2 3 a1 a2 a3 b1 b2 b3 aa1 aa2 aa3 a2a a3a
$ ls a!(*3*)
a1  a2  a2a  aa1  aa2
Related Question