0

I have a list of file names as output of certain command. I need to find each of these files in a given directory.

I tried following command:

ls -R /home/ABC/testDir/ | grep "\.java" | xargs find /home/ABC/someAnotherDir -iname

But it is giving me following error:

find: paths must precede expression: XYZ.java

What would be the right way to do it?

sachinpkale
  • 989
  • 3
  • 14
  • 35

2 Answers2

3
ls -R /home/ABC/testDir/ | grep -F .java | 
    while read f; do find . -iname "$(basename $f)"; done

You can also use ${f##*/} instead of basename. Or;

find /home/ABC/testDir -iname '*.java*' | 
 while read f; do find . -iname "${f##*/}"; done

Note that, undoubtedly, many people will object to parsing the output of ls or find without using a null byte as filename separater, claiming that whitespace in filenames will cause problems. Those people usually ignore newlines in filenames, and their objections can be safely ignored. (As long as you don't allow whitespace in your filenames, that is!)

A better option is:

find /home/ABC/testDir -iname '*.java' -exec find . -iname {}

The reason xargs doesn't work is that is that you cannot pass 2 arguments to -iname within find.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • Thanks. That solved my problem. Is there any reason xargs and pipe redirection is not working with find? – sachinpkale Feb 20 '13 at 03:28
  • 1
    You could have used the `-p` flag of xargs to figure it out : it runs xargs in interactive mode, printing each command it's about to execute. The problem here was that xargs generated a _single_ `find` command with **all** the filenames appended. In this case, you simply needed the `--max-args` option, to launch 1 `find` command for each filename in your list : `ls -R /home/ABC/testDir/ | grep "\.java" | xargs --max-args=1 find /home/ABC/someAnotherDir -iname` – Miklos Aubert Feb 20 '13 at 09:46
0

find /home/ABC/testDir -name "\.java"

rdbmsa
  • 296
  • 3
  • 14
  • This would list .java files in testDir. I want to find all the .java files that are present in testDir, in the current directory. Maybe I was not clear enough. Let me edit the example. – sachinpkale Feb 20 '13 at 03:20