heaven heaven - 7 months ago 21
Bash Question

How to script to go to the deepest folder directory from parent directory to execute a command?

I am trying to automate converting .vmx to .ova by ovftool, and these .vmx files are generated from ghettoVCB. So I am writing a script to get converting automation working.

My question is how do I write a shell script that goes through each directory from a parent_directory and executes a command in each directory? Or could move everything from the deepest folder to parent_directory? (This solution may take time consuming to move those files from the deepest folder to parent_directory).

The directory structure is as follows:
parent_directory/automation/automation-2016-04-18_19-08-32/automation.vmx
parent_directory/bulls/bulls-2016-04-18_18-28-57/bulls.vmx

Here is another structure layout

parent_directory


  • automation


    • automation-2016-04-18_19-08-32


      • automation.vmx



  • bulls


    • bulls-2016-04-18_18-28-57


      • bulls.vmx





The name of subfolders from parent_directory does not follow patterns. Could be any name.
The folder "automation-2016-04-18_19-08-32" is the name of subfolder + date + time.

Answer

Approach 1

move everything from the deepest folder to parent_directory

This command will search subdirectories of the current directory, find all .vmx files, and move them to the current directory:

find . -type f -name '*.vmx' -exec mv {} . \;

Approach 2

write a shell script that goes through each directory from a parent_directory and executes a command in each directory

The following command will search for every subdirectory of the current directory and execute command in it:

find . -type d -execdir command \;

If you want to run command in every directory that contains .vmx files and supply the names of those .vmx files as arguments to command, then run:

find . -type f -name '*.vmx' -execdir command {} +

Alternatively, suppose we want to run the command once for each .vmx file that we find:

find . -type f -name '*.vmx' -exec command {} \;