Via Cà Matta 2 - Peschiera Borromeo (MI)
+39 02 00704272
info@synaptica.info

Linux Tip of the day: Copying Files by pattern to a Temporary Directory with a Shell Command

Digital Innovation Partner

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!

🔍 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 second find command inside the directory to list all files (-type f).
  • | while read -r file; do ... done: The files found are then piped into a while loop that reads each file one by one.
  • cp "$file" ./tmp/$(basename "$file"): Finally, for each file read, a cp 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!