2012-07-27 44 views
0

我有一個bash腳本,由其他人創建,我需要修改一點。 由於我是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個文件。

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

回答

1

這很簡單 - 只要你想要前20個文件,只需通過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 "-----------------------" 
0

使用head -n 20(由Peter提出)。補充說明:該腳本效率非常低,因爲它運行兩次find。當命令第一次運行時,您應該考慮使用tee來生成臨時文件,然後對此文件的行進行計數並刪除文件。

0

我會personnaly喜歡做這樣的:

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