Master Linux find with exec: List, Delete, Move, and Search Files Efficiently
This guide shows how to combine the Linux find command with the -exec (or -ok) option to locate files by pattern and then automatically list details, delete, move, or search within them, providing practical examples and safe‑mode usage for robust batch operations.
The find command is a high‑frequency tool on Linux for locating files by name, date, or regular expression, but by itself it only lists matches.
To perform further actions on the found files, the -exec (or safe -ok) option can be used, which appends a command such as rm, mv, or grep to each match. The syntax ends with an escaped semicolon \; and uses braces {} as placeholders for the current file.
Example 1: List detailed info of all .o files
find . -name "*.o" -type f -exec ls -l {} \;The command finds every .o file in the current directory tree and runs ls -l on each, producing a detailed listing as shown in the screenshot.
Example 2: Delete all .o files
find . -name "*.o" -exec rm {} \;After execution, every .o file is removed. No output is produced, confirming the deletion.
Example 3: Safe deletion with confirmation
find . -name "*.o" -ok rm {} \;The -ok variant prompts the user for confirmation before running rm on each file, preventing accidental mass deletions.
Example 4: Search for a keyword inside matched header files
find . -name "*.h" -exec grep -rns "hello" {} \;This command first filters for .h files and then runs grep -rns "hello" on each, efficiently locating occurrences of the keyword without scanning the entire source tree.
Example 5: Copy matched files to a build directory
find . -name "*.o" -exec cp {} build \;All .o files are copied into the build directory, demonstrating how -exec can be used for bulk file relocation.
By combining find with -exec or -ok, administrators and developers can automate repetitive file‑management tasks, improve efficiency, and add safety checks where needed.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
