2015-01-13 49 views
1

我有這while while循環下面,我試圖得到下面列出的結果。循環的目的是通過BookDB.txt並找到所有匹配標題或作者的模式,並在發現循環將打印出來,但目前我的問題是,我試圖在列表之前插入一行所有匹配模式稱爲「找到的記錄數量:X」。顯示while while循環不確定的某些事情

number of records found: X 
Title,Author,Price,QtyAvailable,QtySold 

我不知道哪裏放線拿到備案的,因爲如果我把它內環路將成爲重複的,我想,以避免重複發現的記錄數線

#matching item 1  
number of records found: X 
Title,Author,Price,QtyAvailable,QtySold 

#matching item 2 
number of records found: X 
Title,Author,Price,QtyAvailable,QtySold 

但我不確定我應該如何修改我的代碼來做到這一點。需要幫助請,文件的輸入是

Title:Author:Price:QtyAvailable:QtySold 


function search_book 
{ 
echo "Enter Title: " 
read title_r 
echo "Enter Author: " 
read author_r 
while read -r result 
do 
title=$(echo "$result" | cut -f 1 -d ":") 
author=$(echo "$result" | cut -f 2 -d ":") 
price=$(echo "$result" | cut -f 3 -d ":") 
qty_ava=$(echo "$result" | cut -f 4 -d":") 
qty_sold=$(echo "$result" | cut -f 5 -d ":") 
if echo "$title" | grep -iq "$title_r" && echo "$author" | grep -iq "$author_r"; 
then 
record=$(grep -io "$title" BookDB.txt | sort | uniq -c) 
echo -e "$title,$author,$price,$qty_ava,$qty_sold"  
fi 
done < ./BookDB.txt 
echo "" 
echo "Number of records found: " $record | cut -f1-6 -d" " 
echo "" 

    } 
+0

這是怎麼回事?輸出是否錯誤?你有錯誤嗎?你想要改變什麼? –

+0

嗨,我想改變它,以便記錄顯示將首先在標題和其他細節之前,但我不確定如何這樣做,因爲如果我把循環記錄線將有重複,我只想要1行顯示記錄 – Ken

回答

1

你剛剛需要把記錄行while循環前,首先呼應記錄則循環將通過程序運行,並顯示您的匹配模式的列表沒有任何重複的記錄

function search_book 
{ 
    echo "Enter Title: " 
    read title_r 
    echo "Enter Author: " 
    read author_r 
    record=$(grep -io "$title_r" BookDB.txt | sort | uniq -c) 
    echo "Number of records found: " $record | cut -f1-6 -d" " 
    while read -r result 
    do 
    title=$(echo "$result" | cut -f 1 -d ":") 
    author=$(echo "$result" | cut -f 2 -d ":") 
    price=$(echo "$result" | cut -f 3 -d ":") 
    qty_ava=$(echo "$result" | cut -f 4 -d":") 
    qty_sold=$(echo "$result" | cut -f 5 -d ":") 
    if echo "$title" | grep -iq "$title_r" && echo "$author" | grep -iq "$author_r"; 
    then 
    #record=$(grep -io "$title" BookDB.txt | sort | uniq -c) 
    echo -e "$title,$author,"\$"$price,$qty_ava,$qty_sold" 
    fi 
    done < ./BookDB.txt 
    echo "" 
    #echo "Number of records found: " $record | cut -f1-6 -d" " 
    echo "" 
    main_menu 

} 
+0

哦,我看到了,我粗心的錯誤 – Ken