2013-08-02 22 views
0

我試圖編寫一個腳本來讀取一個帶有文件名的文件,並輸出是否在目錄中找到這些文件。使用bash數組循環查找列表中的文件

按道理我想它是這樣的:

$filelist = prompt for file with filenames 
$directory = prompt for directory path where find command is performed 

new Array[] = read $filelist line by line 

for i, i > numberoflines, i++ 
    if find Array[i] in $directory is false 
     echo "$i not found" 
export to result.txt 

我一直有一個很難得到猛砸要做到這一點,任何想法?

+0

您可以使用'if [-f「$ dir/$ file」]'來查看'file'是否在'dir'內。 – Bill

+0

在這裏搜索'[bash]找到xargs',你應該找到許多文章給你的想法。祝你好運。 – shellter

回答

0

首先,我只假設所有文件名都在標準輸入中提供。例如,如果文件names.txt包含文件名和check.sh是腳本,你可以調用它像

cat names.txt | ./script.sh 

,以獲得所需的行爲(即使用文件名從names.txt)。

其次,內部script.sh可以循環標準輸入的所有線路如下超過

while read line 
do 
    ... # do your checks on $line here 
done 

編輯:我適應我的答案使用標準輸入,而不是命令行參數,由於問題表示通過@rici。

+1

如果有任何文件名中有空格,那就會中斷。 ''$ @''不會保存它,因爲這些單詞已經被$(cat filenames.txt)分開了(好吧,你沒有使用'$()',但它不會生成任何差異和反引號已棄用)。 – rici

+0

@rici您說得對。最好是逐行讀取輸入,而不是通過參數。 – chris

+0

我將如何使用腳本內部的垂直管道?我希望能夠做到這一點,一個人可以在Finder中雙擊。 – sxflynn

0
while read dirname 
do 
    echo $dirname >> result.txt 
    while read filename 
    do 
    find $dirname -type f -name $filename >> result.txt 
    done <filenames.txt 
done <dirnames.txt 
+0

我將如何根據腳本的位置製作'dirname'動態,即。腳本位於'〜/ project/script.sh'中,所以我想'dirname'自動成爲'〜/ project /'?與'filenames.txt'相同**編輯:**抱歉nvm,我搜索了stackexchange並在'http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory找到了答案 - 存儲在' – sxflynn

+0

我[我找到了答案](http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in)給我的評論關於動態目錄的問題。 – sxflynn