如何在&q;find(.)-exec(.){};&bash命令的{}中使用替身字符串?

人气:461 发布:2022-10-16 标签: bash find

问题描述

如何使用替身在{}中通过bash的"查找"找到字符串?

举个例子,我想在下面?把替身的"in"改成"out":

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

即对所有"*.in"文件执行

python somescript.py somefile.in somefile.out

推荐答案

find没有替换功能。您需要调用shell。

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

$0是文件名,${0%.in}删除.in后缀。

或者,在bash(但不是普通sh)中,运行shopt -s globstar以启用递归目录扩展(如果存在没有任何匹配的.in文件的风险),则运行shopt -s nullglob,并使用for循环而不是find

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

812