簡體   English   中英

Bash遍歷目錄中的文件

[英]Bash looping through files in Directory

我有一個由其他人創建的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個文件。

我是否需要將整個腳本放入循環方法中?

這很容易-只要您想要前20個文件,只需將第一個find命令通過head -n 20傳遞即可。 但是我無法抗拒清理的過程:按照編寫的方式,它會運行一次find兩次,一次打印文件名,一次計數它們。 如果要搜索的文件很多,那是浪費時間。 其次,將腳本的實際內容包裝在一個函數中( report )沒有多大意義,而使函數exit (而不是return ing)則意義不大。 最后,我喜歡用雙引號和反斜杠保護文件名(使用$()代替)。 因此,我進行了一些清理工作:

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

使用head -n 20 (由Peter提議)。 附記:劇本是非常低效的,因為它運行find兩次。 您應該考慮在第一次運行該命令時使用tee來壓縮一個臨時文件,然后計算該文件的行數並刪除該文件。

我個人喜歡這樣做:

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 find "$SRC" -iname "*.aws" -type f -print0 | head -20

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM