Shell循环遍历特定目录中的所有文件



如何使用shell脚本循环遍历特定目录中的所有文件?我在当前工作目录中有一个目录,它是.temp。在.temp内部有另一个目录索引,其中有一些文件。

我尝试过以下几种:

for file in ./.temp/index/*
do 
echo "File in index: $file"
done 
for file in "./.temp/index"/*
do 
echo "File in index: $file"
done 

但是,它将$file打印为./.temp/index/$file。例如:

File in index: ./.temp/index/first.txt
File in index: ./.temp/index/second.txt
File in index: ./.temp/index/third.txt
...

是否有符合POSIX的方式来循环该目录中的实际文件?

for _file in `find . -type f`;
do
echo "File: $_file";
done

-type f将在目录中查找文件。您可以根据需要添加其他筛选器。

您可以通过使用find和-printf来避免一起使用循环,使用-f只打印文件名:

find ./.temp/index -maxdepth 1 -type f -printf "File in index: %fn"

最新更新