在Bash中循环浏览目录 [英] Looping through directories in Bash

查看:74
本文介绍了在Bash中循环浏览目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求脚本将cd移至目录,然后删除子目录中的除少数几个文件以外的所有文件,但不要理会这些文件夹.对每个我需要保留的文件使用switch/case会有所帮助吗?

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/cases for each file I need to preserve?

理想情况下,我认为它应该继续搜索更多的子目录,而不是让我拥有只向下搜索两个级别的嵌套循环.

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).

这是我的代码:

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

推荐答案

如何?

$ find /Users/YourName/Desktop/Test -type f -maxdepth 2 -not -name watch.log -delete


  • -type:仅查找文件
  • -maxdepth:最多下降两个水平
  • -not -name(组合键):从搜索中排除watch.log
  • -delete:删除文件
  • -type: look for files only
  • -maxdepth: go down two levels at most
  • -not -name (combo): exclude watch.log from the search
  • -delete: deletes files


首先尝试不带-delete标志的上述命令.这将打印出将要删除的文件列表.

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.

这篇关于在Bash中循环浏览目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆