Linux Tip of the day: Copying Files by pattern to a Temporary Directory with a Shell Command
Have you ever needed to copy specific files from a series of directories that match a certain pattern? If so, here’s a shell command that might be just what you need!
1 2 3 4 |
find . -type d -name 'AXR*' -exec find {} -type f \; | while read -r file; do cp "$file" ./tmp/$(basename "$file") done |
🔍 Here’s What This Command Does:
find . -type d -name 'AXR*' -exec find {} -type f \;
: This part of the command searches all directories in the current directory (.
) whose names start with “AXR”. For each directory found, it runs a secondfind
command inside the directory to list all files (-type f
).| while read -r file; do ... done
: The files found are then piped into awhile
loop that reads each file one by one.cp "$file" ./tmp/$(basename "$file")
: Finally, for each file read, acp
command is executed to copy the file into the./tmp
directory, keeping the file’s original name using$(basename "$file")
.
⚙️ In Practice: This command is useful when you need to copy all files from specific directories that match a certain pattern (e.g., directories starting with “AXR”) into a temporary directory named tmp
. Each file is copied while retaining its original name.
💡 Note: Make sure the tmp
directory exists before running this command, otherwise the cp
command will fail.
This command is a great example of how to combine different Unix shell tools to solve complex problems in an elegant and efficient way!