Search code examples
bashfind

How to substitute string in {} in "find (...) -exec (...) {} \;" bash command?


How can I substitute a string in {} as found by bash's ´find´?

For instance I would like ? below to substitute "in" by "out":

find . -name "*.in" -exec python somescript.py {} ? \;

i.e. to execute for all "*.in" files

python somescript.py somefile.in somefile.out


Solution

  • find doesn't have a substitution feature. You need to call a shell.

    find . -name "*.in" -exec sh -c 'python somescript.py "$0" "${0%.in}.out"' {} \;
    

    $0 is the file name, ${0%.in} removes the .in suffix.

    Alternatively, in bash (but not in plain sh), run shopt -s globstar to enable recursive directory expansion (and shopt -s nullglob if there's a risk that there won't be any matching .in file) and use a for loop instead of find.

    for x in **/*.in; do
      python somescript.py "$x" "${x%.in}.out"
    done