shell脚本显示不起作用

时间:2015-01-13 05:45:54

标签: shell

我在下面的代码中显示了基于用户输入的字段,程序将抓住其他剩余字段,我想看到的正确显示是

Found 2 records
The Hunger Games, Suzanne Collins, 1, 1, 1
The Hunger Games, Test, 1, 1, 1

但是显示屏下面的当前代码是

Found 2
the hunger games
the hunger games, suzanne collins
test, 1
1, 1
1, 1
1

文件的输入是

The Hunger Games:Suzanne Collins:1:1:1
The Hunger Games:test:1:1:1

希望有人可以帮助我

echo "Enter Title: "
read title
echo "Enter Author: "
read author
result=$(grep -ise "$title\:$author" BookDB.txt)
record=$(grep -io "$title" BookDB.txt | uniq -c)
if [ "$result" != "" ] && [ "$author" == "" ]
then 
echo "found: " $record "records" | awk '{print $1  $2}'
echo "" 
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 ":")
echo ""
echo -e "$title", "$author", ""\$"$price", "$qty_ava", "$qty_sold"

2 个答案:

答案 0 :(得分:1)

不要削减,只需尝试使用sed,如:

sed 's/:/, /g' file.txt

它将搜索“:”并用“,”

替换它的每一个匹配项

答案 1 :(得分:1)

好吧,我的方法并不是最好的,但是为记录运行双倍循环,而不是先打印所有细节来计算记录,再次循环来获取详细信息。它不是最好或最有效的方法

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
let record++

fi  
done < ./BookDB.txt

echo "Number of books found: " $record  
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
let record++
echo -e "$title,$author,"\$"$price,$qty_ava,$qty_sold"      
fi  
done < ./BookDB.txt
#echo "Number of books found: " $record 
echo ""