在 Bash 中循环目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5665169/
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
Looping through directories in Bash
提问by infmz
I require the script to cd
to a directory, then delete all but a few files in sub-directories—but leave the folders alone. Would it help to use switch
/case
s for each file I need to preserve?
我需要脚本到cd
一个目录,然后删除所有子目录中的文件,但不要理会文件夹。对我需要保留的每个文件使用switch
/ case
s会有所帮助吗?
Ideally, I think it should keep searching for further sub-dirs, instead of me having nested loops which only search down two levels.
理想情况下,我认为它应该继续搜索更多的子目录,而不是我有只搜索两个级别的嵌套循环。
Another problem is that it skips folders with spaces (though this isn't an issue with the volumes that the script will run, for now).
另一个问题是它会跳过带有空格的文件夹(尽管目前这不是脚本将运行的卷的问题)。
Here's my code:
这是我的代码:
for i in /Users/YourName/Desktop/Test/* ; do
if [ -d "$i" ]; then
cd $i
for j in "$i"/* ; do
if [ -d "$j" ]; then
cd $j
for k in $(ls *); do
if [ ! $k == "watch.log" ]; then
echo $k
rm -rf $k
fi
done
fi
done
fi
done
采纳答案by Hai Vu
How about this?
这个怎么样?
$ find /Users/YourName/Desktop/Test -type f -maxdepth 2 -not -name watch.log -delete
Explanation
解释
-type
: look for files only-maxdepth
: go down two levels at most-not -name
(combo): excludewatch.log
from the search-delete
: deletes files
-type
: 只查找文件-maxdepth
: 最多下两层-not -name
(组合):watch.log
从搜索中排除-delete
: 删除文件
Recommendation
推荐
Try out the above command without the -delete
flag first. That will print out a list of files that would have been deleted.
首先尝试不带-delete
标志的上述命令。这将打印出将被删除的文件列表。
Once you're happy with the list, add -delete
back to the command.
一旦您对列表感到满意,请-delete
重新添加到命令中。
回答by static_rtti
You should use find
:
你应该使用find
:
for i in $(find . -type d)
do
do_stuff "$i"
done
If you really have a lot of directories, you can pipe the output of find into a while read
loop, but it makes coding harder as the loop is in another process.
如果您确实有很多目录,您可以将 find 的输出通过管道传输到一个while read
循环中,但由于循环在另一个进程中,因此编码变得更加困难。
About spaces, be sure to quote the variable containing the directory name. That should allow you to handle directories with spaces in their names fine.
关于空格,请务必引用包含目录名称的变量。这应该允许您很好地处理名称中带有空格的目录。
回答by Aif
Using find? You can use several parameters, including depth, file age (as in stat), perms etc...
使用查找?您可以使用多个参数,包括深度、文件年龄(如在 stat 中)、perms 等...
find . -maxdepth 2