Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I want to exclude some directories from searching files and than run the find command to find required files. I am using below command

find . -maxdepth 1 -type d | grep -E -i 'sensors' | grep -v '.test' | xargs find -name '*.java'

But it throws following error

find: paths must precede expression
share|improve this question

3 Answers 3

up vote 1 down vote accepted

The first find will cause the second find to list everything twice unless you exclude the current directory as well. This happens because the output of the first find contains a period.

$ find -maxdepth 1 -type d -print0 |
   grep -z -v -Ee 'sensors|\.test' |
   xargs.exe -0 -I% find % -name '*.java' |
   sort
  ./dirz/3.java
  ./dirz/3.java
  ./foo/2.java
  ./foo/2.java
  ./moo/1.java
  ./moo/1.java

You're better off doing something like this instead:

$ find . -type f -name \*java | grep -v -Ee './(sensors|\.test)'
./dirz/3.java
./foo/2.java
./moo/1.java

Or even:

$ echo dirz foo moo | tr \  \\n  > .search-dirs

$ find `cat .search-dirs` -type f -name \*java
dirz/3.java
foo/2.java
moo/1.java
share|improve this answer

Use xargs' -i option which like in find's -exec option replaces {} with the paths.

... | xargs -i find "{}" -name '*.java'
share|improve this answer

You can do it directly in find; no need to involve grep or xargs.

With a directory structure like:

$ ls *
a_sensors_directory:
my_file.java  my_non_java_file.txt

a_sensors_directory.test:
my_file.java  my_non_java_file.txt

something_else:
my_file.java  my_non_java_file.txt

, this GNU find command will pick out files ending in .java in directories in the current working directory that contain the word sensors, but does not end in .test (if I interpreted your question correctly):

$ find -type f -ipath './*sensors*' -not -ipath './*.test/*' -iname '*.java'
./a_sensors_directory/my_file.java

man find should explain the switches clearly and probably better than I would.

Piping is powerful, but the base tools handle many scenarios by themselves in a more straightforward manner. This avoids unnecessary process forks and keeps subtle errors to a minimum.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.