Bash遍历目录中的文件 [英] Bash looping through files in Directory

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

问题描述

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

I have a bash script, created by someone else, that I need to modify a little. Since I'm new to Bash, I may need a little help with some common commands.

该脚本简单地(递归地)遍历目录以查找特定的文件扩展名.这是当前的脚本:(runme.sh)

The script simply loops through a directory (recursively) for a specific file extension. Here's the current script: (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的文件的列表

I simply type #./runme.sh and I can see a list of all files with the extension of .aws

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

My primary goal is to limit the search. (some directories have way too many files) I would like to run the script, limiting it to just 20 files.

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

Do I need to place the entire script into a loop method?

推荐答案

这很简单-只要您想要前20个文件,只需通过 head将第一个 find 命令通过管道传送-n 20 .但是我无法拒绝它的清理工作:按照编写的方式,它两次运行 find ,一次打印文件名,一次对它们进行计数.如果要搜索的文件很多,那是浪费时间.其次,将脚本的实际内容包装在一个函数中( report )并没有多大意义,而是使用函数 exit (而不是 return ing)甚至更少.最后,我喜欢用双引号和反斜杠保护文件名(改为使用 $()).因此,我进行了一些清理工作:

That's easy -- as long as you want the first 20 files, just pipe the first find command through head -n 20. But I can't resist a little cleanup while I'm at it: as written, it runs find twice, once to print the filenames and once to count them; if there are a lot of files to search, this is a waste of time. Second, wrapping the actual content of the script in a function (report) doesn't make much sense, and having the function exit (rather than returning) makes even less. Finally, I like to protect filenames with double-quotes and hate backquotes (use $() instead). So I took the liberty of a bit of cleanup:

#! /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 "-----------------------"

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

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