3

I have a java class file which I need to run on every file in a directory. I'm currently using the following command to run the program on every file in the directory

find . -type f -exec java JavaProgram {} \;

However instead of displaying the result in the terminal, I need it to output the result of each call to a separate file. Is there a command I could use that can recursively call a java program on a whole directory and save the terminal output of each call to a separate file?

Sort of like running java JavaProgram inputfile > outputdir/outputfile but recursively through every file in a directory where 'inputfile' and 'outputfile' have the same name.

2 Answers 2

4

How about

for i in $(find . -type f)
do
    java JavaProgram $i > ${i}.out
done

This will run the program against each file and write the output to filename.out in the same directory for each file. This approach is slightly more flexible than the one-line subshell approach in that you can do arbitrary transformation to generate the output filename, such as use basename to remove a suffix.

6
  • when I run the first line for i in $(find . -type f) I get the error Illegal Variable name. Does that have to do with the variable i? May 5, 2012 at 6:02
  • Looping over the output from find like that will break on filenames with spaces or other whitespace characters: stackoverflow.com/questions/301039/…
    – ataylor
    May 5, 2012 at 6:13
  • What OS and shell are you using? This syntax is for bash/ksh. And, @ataylor is correct, this doesn't handle filenames with spaces. FOr that you should investigate xargs. May 5, 2012 at 6:14
  • Im using Ubuntu Linux. And the files have no spaces. May 5, 2012 at 19:42
  • @OliviaPanda that doesn't actually tell us what shell you're using; try echo $SHELL to get the answer.
    – the paul
    May 5, 2012 at 22:50
2

Just exec a subshell to do the redirection. For example:

find . -type f -exec sh -c "java JavaProgram {} > outputdir/{}" \;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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