Dynamic File Operations with `find -exec` and `shuf`
Quick Tip
Dynamic File Operations with `find -exec` and `shuf`
Challenge: You need to perform a specific action on a subset of files that are dynamically selected, perhaps randomly, from a directory. Executing commands on found files individually can be slow and cumbersome.
The Solution: Combine `find` with `shuf` and `xargs` for efficient, randomized execution of commands on files.
find . -type f -name "*.log" -print0 | shuf -z -n 5 | xargs -0 rm
Why it works: `find -print0` outputs filenames separated by null characters, which `shuf -z` can then shuffle and select a specific number (`-n 5`) of, also null-delimited. `xargs -0` safely processes these null-delimited arguments, allowing commands like `rm` to operate on the selected files.
Pro-Tip: Replace `rm` with any other command like `mv` or `cp` to perform different operations on the randomly selected files.
Linux Tips & Tricks | © ngelinux.com | 4/26/2026
