MacOS – Unix command to recursively copy JPG files in a complex directory tree

command linemacosterminal

I have a large directory tree structure that contains multiple JPG files in each directory root and their subsequent subdirectories. I need to recursively extract a single JPG file from each directory root and copy them all to another location whilst maintaining the same tree structure and ignoring the other files. The JPG filenames that I need to extract all are tagged with "RNav.jpg". I experimented with the cp command and wild card but I could not get it to work. I'm running Mavericks and I'm a novice when it comes to UNIX command-lines.

The existing structure is as follows: (up to 500 directories)

  • VNAME/PNAME1/PNAME1_RNav.jpg
  • VNAME/PNAME2/PNAME2_RNav.jpg
  • VNAME/PNAME3/PNAME3_RNav.jpg
  • VNAME/PNAME4/PNAME4_RNav.jpg

Best Answer

You can also use rsync -R (--relative) or --parents in GNU cp:

rsync -R */*/*.RNav.jpg /path/to/target
gcp --parents */*/*RNav.jpg /path/to/target
find . -name \*RNav.jpg -exec rsync -R {} /path/to/target \;
find . -name \*RNav.jpg -exec gcp --parents {} /path/to/target \;