循环浏览给定目录中的文件 [英] Loop through files in a given directory
本文介绍了循环浏览给定目录中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图遍历用户指定目录中的每个文件. 这是我的代码:
I am trying to loop through every file in a user specified directory. Here's my code:
clear
echo "enter the directory path: \n"
read directory
for file in $directory; do
echo $file
done
我的输入,例如:/home/user/Downloads
我得到的输出:/home/user/Downloads
如果我使用
clear
for file in *; do
echo $file
done
可以,但是只显示当前目录的内容
It works, but it shows only the contenets of current directory
推荐答案
如果只希望非递归地将文件放在当前目录中,请结合使用:
If you only want the files non-recursively in the current directory, combine what you have:
read -p 'Enter the directory path: ' directory
for file in "$directory"/*; do
echo "$file"
done
如果您想递归循环并且拥有bash 4,那就不难了:
If you want to loop recursively and you have bash 4, it's not much harder:
shopt -s globstar
for file in "$directory"/**/*; do …
但是,如果您只使用bash 3,则最好使用find
.
But if you only have bash 3, you'd be better off using find
.
find "$directory"
这篇关于循环浏览给定目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文