【问题标题】:Bash looping through files in DirectoryBash 循环遍历目录中的文件
【发布时间】:2012-07-25 18:38:11
【问题描述】:

我有一个由其他人创建的 bash 脚本,我需要对其进行一些修改。 由于我是 Bash 新手,可能需要一些常用命令的帮助。

脚本简单地循环遍历一个目录(递归)以获得特定的文件扩展名。 这是当前脚本:(runme.sh)

#! /bin/bash
SRC=/docs/companies/

function report()
{
    echo "-----------------------"
    find $SRC -iname "*.aws" -type f -print
    echo -e "\033[1mSOURCE FILES=\033[0m" `find $SRC -iname "*.aws" -type f -print |wc -l`
    echo "-----------------------"
exit 0
}

report

我只需键入 #./runme.sh 即可看到所有扩展名为 .aws 的文件的列表

我的主要目标是限制搜索。 (某些目录的文件太多) 我想运行脚本,将其限制为 20 个文件。

是否需要将整个脚本放入循环方法中?

【问题讨论】:

    标签: bash loops


    【解决方案1】:

    这很简单——只要您想要前 20 个文件,只需将第一个 find 命令通过管道传输到 head -n 20。但是当我在处理它时,我无法抗拒一点清理:正如所写,它运行find 两次,一次打印文件名,一次计算文件名;如果要搜索的文件很多,这是浪费时间。其次,将脚本的实际内容包装在一个函数 (report) 中没有多大意义,而拥有函数 exit(而不是 returning)则更少。最后,我喜欢用双引号保护文件名,讨厌反引号(改用$())。所以我冒昧地进行了一些清理:

    #! /bin/bash
    SRC=/docs/companies/
    
    files="$(find "$SRC" -iname "*.aws" -type f -print)"
    if [ -n "$files" ]; then
        count="$(echo "$files" | wc -l)"
    else # echo would print one line even if there are no files, so special-case the empty list
        count=0
    fi
    
    echo "-----------------------"
    echo "$files" | head -n 20
    echo -e "\033[1mSOURCE FILES=\033[0m $count"
    echo "-----------------------"
    

    【讨论】:

      【解决方案2】:

      使用head -n 20(由彼得提议)。补充说明:该脚本效率非常低,因为它运行find 两次。您应该考虑在命令第一次运行时使用tee 生成一个临时文件,然后计算该文件的行数并删除该文件。

      【讨论】:

        【解决方案3】:

        我个人更喜欢这样:

        files=0
        while read file ; do
            files=$(($files + 1))
            echo $file
        done < <(find "$SRC" -iname "*.aws" -type f -print0 | head -20)
        
        echo "-----------------------"
        find $SRC -iname "*.aws" -type f -print
        echo -e "\033[1mSOURCE FILES=\033[0m" $files
        echo "-----------------------"
        

        如果你只想计算,你只能使用find "$SRC" -iname "*.aws" -type f -print0 | head -20

        【讨论】:

          猜你喜欢
          • 2013-09-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多