使用循环不确定某些东西时显示

时间:2015-01-13 12:15:48

标签: shell while-loop

我有这个while循环,我试图得到下面列出的结果。循环的目的是通过BookDB.txt并找到与Title或Author匹配的所有模式,并在找到循环后将其打印出来,但目前我的问题是我试图在列表前插入一行所有匹配模式称为“找到的记录数:X”。

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 ""

  }

1 个答案:

答案 0 :(得分: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

}