Copying Files with Directory Structure | Generated by AI

Home PDF

Given your find command output, you want to copy all the .log files to /Users/lzwjava/projects/logs while preserving their directory structure. For example, a file like ./CoreSimulator/FC275C39-59CC-4483-A64E-5D459D7A1D57/system.log should end up as /Users/lzwjava/projects/logs/CoreSimulator/FC275C39-59CC-4483-A64E-5D459D7A1D57/system.log. I’ll show you how to achieve this using find combined with cp or rsync, ensuring the directory hierarchy is maintained.


Solution 1: Using find with cp

You can use find to locate the .log files and cp with the --parents option to copy them while preserving their directory structure.

Command

find . -name "*.log" -exec cp --parents {} /Users/lzwjava/projects/logs \;

Explanation

Result

Before Running


Solution 2: Using rsync

rsync is another powerful tool that can copy files while preserving directory structure, and it’s often more efficient for bulk operations.

Command

find . -name "*.log" -exec rsync -R -a {} /Users/lzwjava/projects/logs \;

Explanation

Result

Same as above—files are copied with their full relative paths intact.

Before Running


Verifying the Copy

After running either command, check the destination:

ls -R /Users/lzwjava/projects/logs

You should see:

/Users/lzwjava/projects/logs:
CoreSimulator

/Users/lzwjava/projects/logs/CoreSimulator:
CoreSimulator.log  FC275C39-59CC-4483-A64E-5D459D7A1D57  Simulator.log

/Users/lzwjava/projects/logs/CoreSimulator/FC275C39-59CC-4483-A64E-5D459D7A1D57:
com.apple.itunesstored  system.log

/Users/lzwjava/projects/logs/CoreSimulator/FC275C39-59CC-4483-A64E-5D459D7A1D57/com.apple.itunesstored:
itunesstored.log

Key Notes


Which to Choose?

Both will work for your case. I recommend starting with cp --parents for simplicity.


mkdir -p /Users/lzwjava/projects/logs
find . -name "*.log" -exec cp --parents {} /Users/lzwjava/projects/logs \;

Run this from your Logs directory (lzwjava@anonymous Logs %), and you’re set! Let me know if you hit any snags or want to adjust the behavior (e.g., flatten the structure instead).


Back 2025.03.16 Donate