bash 循环遍历给定目录中的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23408782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop through files in a given directory
提问by kulan
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
My input, e.g.: /home/user/Downloads
我的输入,例如: /home/user/Downloads
Output I get: /home/user/Downloads
我得到的输出: /home/user/Downloads
If I use
如果我使用
clear
for file in *; do
echo $file
done
It works, but it shows only the contenets of current directory
它有效,但它只显示当前目录的内容
回答by kojiro
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
If you want to loop recursively and you have bash 4, it's not much harder:
如果你想递归循环并且你有 bash 4,那也没什么难的:
shopt -s globstar
for file in "$directory"/**/*; do …
But if you only have bash 3, you'd be better off using find
.
但是如果你只有 bash 3,你最好使用find
.
find "$directory"
回答by Farid Haq
Try
尝试
dir="${GOL_HOME}/test_dir"
file="file_*.csv"
for file in `cd ${dir};ls -1 ${file}` ;do
echo $file
done
回答by tarun singh
You can write this script
你可以写这个脚本
#!/bin/bash
clear
echo "enter the directory path: \n"
read directory
for file in $directory/*; do
echo $file
done