我试图用find命令对文件计数:
echo "0" > ct
find aaaa/ -type f -exec expr $(cat ct) + 1 > ct \;
cat ct
1
1
1
1
Run Code Online (Sandbox Code Playgroud)
如果我手动执行,它将正常工作:
echo "0" > ct
expr $(cat ct) + 1 > ct
expr $(cat ct) + 1 > ct
expr $(cat ct) + 1 > ct
expr $(cat ct) + 1 > ct
cat ct
4
Run Code Online (Sandbox Code Playgroud)
我会这样:
find aaaa/ -type f -exec printf '%.s.' {} + | wc -c
Run Code Online (Sandbox Code Playgroud)
或者,如果GNU查找可用:
find aaaa/ -type f -printf '.' | wc -c
Run Code Online (Sandbox Code Playgroud)
但是,如果您坚持使用自己的逻辑(即使它不起作用或不实用),则需要在shell中进行命令替换和重定向(请参阅Gordon的注释),例如:
echo 0 > ct
find aaaa/ -type f -exec sh -c 'expr "$(cat ct)" + 1 > ct' \;
cat ct
Run Code Online (Sandbox Code Playgroud)
使用这种方法,将为每个文件生成3个进程(sh,cat,expr),然后创建一个文件,然后将其更新n次,其中n是文件数,这会浪费大量内存和CPU时间。
至少您可以使用批量执行程序,例如:
echo 0 > ct
find aaaa/ -type f -exec sh -c 'expr "$(cat ct)" + "$#" > ct' _ {} +
cat ct
Run Code Online (Sandbox Code Playgroud)