Ubuntu - How to run a command on folder and its subdirectories , and create a file in each folder with the output?

StackOverflow https://stackoverflow.com/questions/23595518

Question

I have a directory myDir with a lot of subdirectories .

I want to execute the following command :

java -cp bin Main

on each and every subdirectory , and then , create (in each subdirectory) a file with the output of the command java -cp bin Main on the subdirectory .

I tried this :

// edited , doesn't work   

But it doesn't really work

Any idea how to do that ?

Thanks

Was it helpful?

Solution 2

Here's my solution:

find /home/a/Desktop/myfolder -type d -exec sh -c '(cd {} && YOUR-COMMAND-GOES-HERE)' ';'

Instead of YOUR-COMMAND-GOES-HERE you can put for example java -cp bin Main

So :

find /home/a/Desktop/myfolder -type d -exec sh -c '(cd {} && java -cp bin Main)' ';'

OTHER TIPS

$i will have the full path (relative to $base). Try instead iterator "$dir/$(basename $i)" or just iterator "$i".

Your script also doesn't do what you say, I suspect you want to run java -cp bin Main inside the if, not on the else (which runs if the file is not a directory).

Either make your java program run itself on all subfolders: list all files from directories and subdirectories in Java

Or pass all folders that you want your java program to create the output into your java program. Something like:

public class Test
{
    public static void main(String[] args)
    {
        if (args != null && args.length>0)
        {
            for (int i = 0; i < args.length; i++)
            {
                System.out.println("Create a file in the folder "+args[i]);
            }
        }
        else {
            System.out.println("args were not provided");
        }
    }
}

And execute it using

java -cp $YOURCLASSPATH Test `find . -type d`

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top