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 Answers2

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.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
  • 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? – Olivia Panda May 05 '12 at 06:02
  • Looping over the output from find like that will break on filenames with spaces or other whitespace characters: http://stackoverflow.com/questions/301039/how-can-i-escape-white-space-in-a-bash-loop-list – ataylor May 05 '12 at 06: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`. – Jim Garrison May 05 '12 at 06:14
  • Im using Ubuntu Linux. And the files have no spaces. – Olivia Panda May 05 '12 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 05 '12 at 22:50
  • output is /usr/local/bin/tcsh. Sorry I'm new to UNIX, is that the shell? – Olivia Panda May 06 '12 at 00:12
2

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

find . -type f -exec sh -c "java JavaProgram {} > outputdir/{}" \;
ataylor
  • 64,891
  • 24
  • 161
  • 189