I have to copy files with a .tmt extension to a folder(ex: \main\allfiles\) from many sub folders under /individualfiles/1/, /individualfiles/2/, /individualfiles/abc/, /individualfiles/xyz/ ... /individualfiles/zzz/.

My issue is after copying all files from one folder, I have to run a java command and then copy again from the next folder and then run the java command again.

We do a copy file by file. After the first file gets copied from /individualfiles/1/, we copy the next file from /individualfiles/1/ and then we go to the next folder /individualfiles/2/ and again copy files individually.

Please let me know how to run the java command after all files have been copied from a folder.

1 Answer 1


You can accomplish this by stringing together a hand full of linux command line utilities.

Something like this,

find . -iname "*.tmt" | xargs dirname | uniq | xargs -I{} sh -c "cp -u {}*.tmt /destination/path && java command.jar"

How it works,

  1. find . -iname "*.tmt" gets all the relative paths with filename of the .tmt type from where you run this and the subfolders
  2. xargs dirname removes the files name leaving you with a list of the relatively pathed directories
  3. uniq removes duplicate directories
  4. xargs -I{} sh -c "cp -u {}*.tmt /destination/path && java command.jar" runs a sh script that copies all .tmt files in the list of directories with .tmt files to a destination folder and if the copy is successful runs java command.jar which should be replaced with your java command.


If your goal is to copy 1 file at a time and then run a command after each file is copied that actually simplifies things. The above commands can be reduced to 1 and 4 or this.

find . -iname "*.tmt" | xargs -I{} sh -c "cp -u {} /destination/path && java command.jar"

This takes every file with the .tmt extension found with find and runs a script to copy and run java command.

  • Thanks for the reply . But as I mentioned above we are copying files one after another . I guess your approach is not as above Apr 29, 2020 at 2:25
  • You mentioned needing to copy the files per directory and then run a command. That's what this code does. If you want to individually copy each file and then run a command after each copy I can make a quick edit to the code above for that.
    – Dan
    Apr 29, 2020 at 2:59
  • Yes that would be great.Yes I need to copy single file at a time . Apr 29, 2020 at 12:53
  • @user1024962 Please see if my edit's address your problem more accurately. If the edit does help please consider up voting and marking the answer as accepted. (Check mark).
    – Dan
    Apr 29, 2020 at 19:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .