4

I want to search a directory for some files using find and a regular expression.

If I do

cd dir
find -E . -type f -regex '^\..*[^~]'

I get a list of files in the directory that match the the regular expression.

However, if I do

find -E ~/dir -type f -regex '^\..*[^~]'

i.e.

find -E /home/adam/dir -type f -regex '^\..*[^~]'

I get no output. How do I specify the directory to be searched by find when using a regular expression?

This is BSD find, as I am on a Mac.

1 Answers1

6

The argument to -regex has to match the whole path that is found. A command like find . finds paths like ./dir/subdir/somefile, while a command like find ~/dir finds paths like /home/adam/dir/subdir/somefile. So your regexp has to match the /home/adam part at the beginning.

The command find -E . -type f -regex '^\..*[^~]' finds files whose name doesn't contain a newline and doesn't end with ~. The . at the beginning always matches since the path begins with ./.

If you were looking for dot files, you'd need to allow for a directory prefix. The following command shows dot files whose name doesn't end in ~:

find -E /whatever -regex '(\n|.)*/\.[^/]*[^~]'

But this is simpler to express with -name:

find /whatever -name '.*[!~]'
  • I was asked to change ~/dir in my question to $HOME/dir, so you might want to update your answer accordingly. At any rate, thanks for the help! – Adam Liter Jul 20 '14 at 05:43
  • @AdamLiter I don't see the point of using $HOME instead of ~. At least quote it. – Gilles 'SO- stop being evil' Jul 20 '14 at 05:54
  • I was asked to change my question so that it was more transparent to new users (though the comments have now been deleted). As I'm not really a regular on this site at all, I just went along with the suggestion. And I didn't want anyone to be confused that you have find ~/dir in your answer rather than find $HOME/dir, as is now in my question. I do agree that there doesn't seem to be much of a point in using $HOME instead of ~. All that being said, maybe these comments are now enough so that users won't be confused by the discrepancy, and you can leave your answer as is. Thanks again! – Adam Liter Jul 20 '14 at 06:02