我正在编写一个脚本,需要在特定文件夹的每个子目录中执行一个操作。
最有效的写法是什么?
我正在编写一个脚本,需要在特定文件夹的每个子目录中执行一个操作。
最有效的写法是什么?
当前回答
方便的俏皮话
for D in *; do echo "$D"; done
for D in *; do find "$D" -type d; done ### Option A
find * -type d ### Option B
选项A适用于中间有空格的文件夹。而且,通常更快,因为它不会将文件夹名称中的每个单词作为单独的实体打印。
# Option A
$ time for D in ./big_dir/*; do find "$D" -type d > /dev/null; done
real 0m0.327s
user 0m0.084s
sys 0m0.236s
# Option B
$ time for D in `find ./big_dir/* -type d`; do echo "$D" > /dev/null; done
real 0m0.787s
user 0m0.484s
sys 0m0.308s
其他回答
避免创建子进程的版本:
for D in *; do
if [ -d "${D}" ]; then
echo "${D}" # your processing here
fi
done
或者,如果你的操作是一个单一的命令,这是更简洁的:
for D in *; do [ -d "${D}" ] && my_command; done
或者一个更简洁的版本(感谢@enzotib)。注意,在这个版本中,每个D的值都有一个尾随斜杠:
for D in */; do my_command; done
for D in `find . -type d`
do
//Do whatever you need with D
done
方便的俏皮话
for D in *; do echo "$D"; done
for D in *; do find "$D" -type d; done ### Option A
find * -type d ### Option B
选项A适用于中间有空格的文件夹。而且,通常更快,因为它不会将文件夹名称中的每个单词作为单独的实体打印。
# Option A
$ time for D in ./big_dir/*; do find "$D" -type d > /dev/null; done
real 0m0.327s
user 0m0.084s
sys 0m0.236s
# Option B
$ time for D in `find ./big_dir/* -type d`; do echo "$D" > /dev/null; done
real 0m0.787s
user 0m0.484s
sys 0m0.308s
找到。-type d -print0 | xargs -0 -n 1 my_command
最简单的非递归方法是:
for d in */; do
echo "$d"
done
末尾的/表示只使用目录。
没有必要
找到 呜 ...