Find files and run one command per result with fd
Use fd extension filters and per-file execution to handle paths containing spaces without shell word splitting.
Updated
in short
Filter files with --type and --extension, then use --exec to pass each result as an argument, including names containing spaces.
Work through these disposable fixtures before adapting the commands to your own files. Run the steps in the same terminal session.
Tools used
Before you start
- Bash on Linux or macOS
- The listed tools installed and available on PATH
Steps
Step 1: Create sample files
All files live in a new temporary directory.
shtrmn_guide_dir="$(mktemp -d)" cd "$trmn_guide_dir" mkdir -p docs cache printf 'alpha\n' > 'docs/release notes.txt' printf 'beta\n' > docs/checklist.txt printf 'skip\n' > cache/output.txt printf 'cache/\n' > .ignore printf '# Notes\n' > docs/readme.mdStep 2: List the selected paths
The dot pattern matches any character in a filename. The extension option omits the leading dot.
shfd --type f --extension txt . docs | sortoutputdocs/checklist.txt docs/release notes.txt
Step 3: Pass each complete path to a command
--exec invokes printf directly. No shell loop splits the name at its space. Execution order may vary, so sort the result.
shfd --type f --extension txt . docs --exec printf 'selected: %s\n' '{}' | sortoutputselected: docs/checklist.txt selected: docs/release notes.txt
Step 4: Confirm the ignored folder stays out
The .ignore file applies even though the search starts at the current directory.
shfd --type f --extension txt . | sortoutputdocs/checklist.txt docs/release notes.txt
Further reading
[fd usage and execution](https://github.com/sharkdp/fd/blob/master/README.md) [fd manual](https://github.com/sharkdp/fd/blob/master/doc/fd.1)
FAQ
- Should I parse this line-by-line output in a script?
- Newlines can occur in filenames. Use --exec directly or a NUL-delimited pipeline with --print0 when handling arbitrary paths.
- Does --exec preserve order?
- Per-file commands can run in parallel. Use --threads 1 when the command needs sequential execution.