find with -exec for actions in Linux CLI - Time & Space Complexity
When using the find command with -exec, we want to know how the time to complete grows as we search more files.
We ask: How does running an action on each found file affect total time?
Analyze the time complexity of the following code snippet.
find /path/to/dir -type f -name "*.txt" -exec wc -l {} \;
This command finds all text files and runs wc -l to count lines in each file.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Running
wc -lon each found file. - How many times: Once for every file that matches the search.
As the number of matching files grows, the total work grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times running wc -l |
| 100 | 100 times running wc -l |
| 1000 | 1000 times running wc -l |
Pattern observation: The total time grows directly with the number of files found.
Time Complexity: O(n)
This means the total time increases in a straight line as you add more files to process.
[X] Wrong: "The -exec action runs only once regardless of files found."
[OK] Correct: Actually, -exec runs once for each matching file, so time grows with the number of files.
Understanding how commands like find -exec scale helps you write scripts that handle many files efficiently and predict how long tasks will take.
What if we changed -exec to -exec ... + to run the action fewer times? How would the time complexity change?