4

So basically I want to add these two cmd lines together

ls *[Aa]* 
ls *[Bb]*

I'm looking for a file that contains both A and B (lower or uppercase) and they can appear more than once.

Here's what I tried:

ls *[Aa]*&&*[Bb]*
epikish
  • 53
  • 6

2 Answers2

6

Using brace expansion

One method is to use brace expansion. Let's consider a directory with these files:

$ ls
1a2a3  1a2b3  1b2A3  1b2b3

To select the ones that have both a and b in either case:

$ ls *{[bB]*[aA],[aA]*[bB]}*
1a2b3  1b2A3

Improvement

A possible issue is how brace expansion behaves if one of the options has no matching files. Consider a directory with these files:

$ ls
1a2a3  1b2A3  1b2b3

Now, let's run our command:

$ ls *{[bB]*[aA],[aA]*[bB]}*
ls: cannot access '*[aA]*[bB]*': No such file or directory
1b2A3

If we don't like that warning message, we can set nullglob and it will go away:

$ shopt -s nullglob
$ ls *{[bB]*[aA],[aA]*[bB]}*
1b2A3

A limitation of this approach though, is that, if neither glob matches, then ls is run with no arguments and consequently it will list all files.

Using extended globs

Let's again consider a directory with these files:

$ ls
1a2a3  1a2b3  1b2A3  1b2b3

Now, let's set extglob:

$ shopt -s extglob

And, let's use an extended glob to find our files:

$ ls *@([bB]*[aA]|[aA]*[bB])*
1a2b3  1b2A3
John1024
  • 74,655
  • 3
    Lest anybody get the idea that brace expansion is a magic wand that solves glob problems, you should probably explain that your answer is equivalent to ls *[bB]*[aA]* *[aA]*[bB]* — just one glob to find files containing B and then A, and another to find files containing A and then B.  (1) The brace version isn’t even any shorter than the straightforward command.  (2) If there are any files whose names contain an alternating sequence of A and B, such as baby or cabstand, they will be listed twice. – G-Man Says 'Reinstate Monica' Sep 26 '16 at 08:43
2

If you don't mind calling grep for aid then

ls *[aA]* | grep -i b

will do as well.

countermode
  • 7,533
  • 5
  • 31
  • 58