Linux bash脚本读取目录中的所有文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7290758/
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
bash script read all the files in directory
提问by mike
How do I loop through a directory? I know there is for f in /var/files;do echo $f;done;
The problem with that is it will spit out all the files inside the directory all at once. I want to go one by one and be able to do something with the $f variable. I think the while loop would be best suited for that but I cannot figure out how to actually write the while loop.
如何遍历目录?我知道有一个for f in /var/files;do echo $f;done;
问题是它会一次性吐出目录中的所有文件。我想一个一个地去,能够用 $f 变量做一些事情。我认为 while 循环最适合这种情况,但我无法弄清楚如何实际编写 while 循环。
Any help would be appreciated.
任何帮助,将不胜感激。
回答by Mu Qiao
A simple loop should be working:
一个简单的循环应该可以工作:
for file in /var/*
do
#whatever you need with "$file"
done
回答by Zsolt Botykai
You can go without the loop:
你可以不用循环:
find /path/to/dir -type f -exec /your/first/command \{\} \; -exec /your/second/command \{\} \;
HTH
HTH
回答by William Pursell
To write it with a while loop you can do:
要使用 while 循环编写它,您可以执行以下操作:
ls -f /var | while read -r file; do cmd $file; done
The primary disadvantage of this is that cmd is run in a subshell, which causes some difficulty if you are trying to set variables. The main advantages are that the shell does not need to load all of the filenames into memory, and there is no globbing. When you have a lot of files in the directory, those advantages are important (that's why I use -f on ls; in a large directory ls itself can take several tens of seconds to run and -f speeds that up appreciably. In such cases 'for file in /var/*' will likely fail with a glob error.)
这样做的主要缺点是 cmd 在子 shell 中运行,如果您尝试设置变量,这会导致一些困难。主要优点是 shell 不需要将所有文件名加载到内存中,并且没有 globbing。当目录中有很多文件时,这些优势很重要(这就是我在 ls 上使用 -f 的原因;在大目录中, ls 本身可能需要几十秒才能运行,而 -f 可以显着加快速度。在这种情况下'for file in /var/*' 可能会因全局错误而失败。)