问题描述
我想对目录中的每个文件做一些事情,所以我有
I want to do something to every file in a directory, so I have
for f in /path/* /path/.*; do
[ -e "$f" ] || continue
do_thing "$f"
done
不幸的是,这也匹配了 .
和 ..
,这在本例中是不可取的.如何避免匹配 .
和 ..
?
Unfortunately, this also matches .
and ..
, which is undesirable in this case. How can I avoid matching .
and ..
?
推荐答案
要对当前目录中的每个文件运行 do_thing
,请尝试:
To run do_thing
on every file in the current directory, try:
find /path -maxdepth 1 -type f -exec do_thing {} \;
这个方法避免了循环,避免解析ls
.
This method avoids looping and avoids parsing ls
.
找到/path
这会启动一个 find
命令并告诉 find 在目录 /path
中查找.
This starts a find
command and tells find to look in directory /path
.
-maxdepth 1
这告诉 find
只在当前目录中查找,而不是进入子目录.
This tells find
to look only in the current directory and not to descend into subdirectories.
-type f
这告诉 find
我们只查找常规文件(而不是目录).
This tells find
that we are only looking for regular files (not directories).
-exec do_thing {} \;
这会在找到的每个文件上运行命令 do_thing
.
This runs command do_thing
on every file found.
这篇关于避免匹配.和 .. 在 POSIX shell 中循环文件时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!