Bash – How to Match Hidden Files with Wildcards

bashdot-filesshellwildcards

How to match the hidden files inside the given directories

for example

If I give the below command it's not giving the result of the hidden files,

 du -b maybehere*/*

how to achieve this simple using a single command instead of using

du -b maybehere*/.* maybehere*/*

as I need to type maybehere twice.

Best Answer

Take advantage of the brace expansion:

du -b maybehere*/{*,.[^.],.??*}

or alternatively

du -b maybehere*/{,.[^.],..?}*

The logic behind this is probably not obvious, so here is explanation:

  • * matches all non-hidden files
  • .[^.] matches files which names started with single dot followed by not a dot; that are only 2 character filenames in the first form.
  • .??* matches hidden files which are at least 3 character long
  • ..?* like above, but second character must be a dot

The whole point is to exclude hard links to current and parent directory (. and ..), but include all normal files in such a way that each of them will be counted only once!

For example the simplest would be to just write

du -b maybehere*/{.,}*

It means that that the list contains a dot . and "nothing" (nothing is between , and closing }), thus all hidden files (which start from a dot) and all non-hidden files (which start from "nothing") would match. The problem is that this would also match . and .., and this is most probably not what you want, so we have to exclude it somehow.


Final word about brace expansion.

Brace expansion is a mechanism by which you can include more files/strings/whatever to the commandline by writing fewer characters. The syntax is {word1,word2,...}, i.e. it is a list of comma separated strings which starts from { and end with }. bash manual gives a very basic and at the same time very common example of usage:

$ echo a{b,c,d}e
abe ace ade
Related Question