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.

how-to4 steps

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

  1. Step 1: Create sample files

    All files live in a new temporary directory.

    sh
    trmn_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.md
  2. Step 2: List the selected paths

    The dot pattern matches any character in a filename. The extension option omits the leading dot.

    sh
    fd --type f --extension txt . docs | sort
    output
    docs/checklist.txt
    docs/release notes.txt
  3. 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.

    sh
    fd --type f --extension txt . docs --exec printf 'selected: %s\n' '{}' | sort
    output
    selected: docs/checklist.txt
    selected: docs/release notes.txt
  4. Step 4: Confirm the ignored folder stays out

    The .ignore file applies even though the search starts at the current directory.

    sh
    fd --type f --extension txt . | sort
    output
    docs/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.

related