如何为每个找到的文件执行多个命令

3

我正在搜索一个特定目录中的文件,并且对于每个找到的文件,我想在这些文件上执行一系列相同的命令。

我使用以下find命令搜索这些文件:

1个回答

3

当然,循环语句是你的好朋友

find . -maxdepth 1 -type f -name "file*" | while read file; do
   echo $file;
   # perform other operations on $file here
done

如果你不是 while 循环的粉丝

$ ls -1 file*
file.txt
file1.txt

$ find . -maxdepth 1 -type f -name "file*" | xargs -n1 -I_val -- sh -c 'echo command1_val; echo command2_val'
command1./file.txt
command2./file.txt
command1./file1.txt
command2./file1.txt

在上面的命令中,使用_val代替{}以避免不必要的引用(受此启发)。

有没有不用 while 循环的方法?也许可以用分组吗? - ronald mcd
@ronaldmcd 我已经更新了我的答案,并提供了一个使用xargs的示例。 - Rakesh Gupta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接