Linux Commands for Batch File Management: find with mv and cp

Post Reply
User avatar
Eli
Senior Expert Member
Reactions: 189
Posts: 5943
Joined: 10 years ago
Location: Tanzania
Contact:

#1

This post explores two powerful Linux commands used for efficiently managing files based on keywords within filenames. Both commands leverage the find command, a versatile tool for locating files within a directory structure, combined with either mv (move) or cp (copy) to perform actions on the found files.

Command 1: Moving Files Based on Filename Keywords

The command:

  1. find /path/to/pdfs -regex '.*Test.*\.pdf\|.*UE.*\.pdf\|.*keyword1.*\.pdf\|.*keyword2.*\.pdf' -exec mv {} /path/to/destination \;

This command searches the /path/to/pdfs directory for PDF files whose filenames contain "Test," "UE," "keyword1," or "keyword2." The -regex option uses a regular expression to match filenames. The \| acts as an "OR" operator, meaning files matching any of the keywords will be selected. The -exec mv {} /path/to/destination \; part executes the mv command, moving each matched file to the /path/to/destination directory.

Important Note: This command moves the files. The original files will be removed from their original location.

Command 2: Copying Files Based on Filename Keywords

The command:

  1. find /path/to/pdfs -regex '.*Test.*\.pdf\|.*UE.*\.pdf\|.*MT765.*\.pdf\|.*765.*\.pdf' -exec cp {} /path/to/destination \;

This command is similar to the first but uses cp instead of mv. It searches the /path/to/pdfs directory for PDF files whose filenames contain "Test," "UE," "MT765," or "765" and copies each matched file to the /path/to/destination directory. The original files remain in their original location.

Important Note: This command copies the files. The original files are preserved in their original locations.

Caveats:

Both commands are case-sensitive. If you need a case-insensitive search, replace -regex with -iregex. Also, these commands move or copy anything within the specified folder that matches the filename pattern. pdf, so make sure the provided keywords are specific enough to avoid unintended actions. For more advanced scenarios or error handling (e.g., what happens if the destination directory doesn't exist?), more sophisticated scripting (using bash or other shell scripting languages) is recommended.
0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
Post Reply
  • Similar Topics
    Replies
    Views
    Last post

Return to “Linux and Unix Based Operating Systems”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 0 guests