我是BASH Shell编程的新手。这是我的问题,我需要从我的文件中拆分数据(用分号分隔符)并搜索是否存在某本书。
文件内容:
Harry Potter - The Half Blood Prince:J.K Rowling:40.30:10:50
The little Red Riding Hood:Dan Lin:40.80:20:10
Harry Potter - The Phoniex:J.K Rowling:50.00:30:20
Harry Potter - The Deathly Hollow:Dan Lin:55.00:33:790
Little Prince:The Prince:15.00:188:9
Lord of The Ring:Johnny Dept:56.80:100:38
Three Little Pig:Andrew Lim:89.10:290:189
All About Ubuntu:Ubuntu Team:76.00:55:133
Catch Me If You Can:Mary Ann:23.60:6:2
Happy Day:Mary Ann:12.99:197:101
Harry:Potter
asd:dsa
Harry:Potter
我的代码在这里:
read -p "Title: " addtitle
read -p "Author: " addauthor
#check if book exists
awk '{
if ($1=="$addtitle" && $2=="$addauthor")
print $0, "found";
else
print $0, "Not found";
}' BooksDB.txt
当我运行我的代码时,它给了我:
Title: Harry
Author: Potter
Harry Potter - The Half Blood Prince:J.K Rowling:40.30:10:50 Not found
The little Red Riding Hood:Dan Lin:40.80:20:10 Not found
Harry Potter - The Phoniex:J.K Rowling:50.00:30:20 Not found
Harry Potter - The Deathly Hollow:Dan Lin:55.00:33:790 Not found
Little Prince:The Prince:15.00:188:9 Not found
Lord of The Ring:Johnny Dept:56.80:100:38 Not found
Three Little Pig:Andrew Lim:89.10:290:189 Not found
All About Ubuntu:Ubuntu Team:76.00:55:133 Not found
Catch Me If You Can:Mary Ann:23.60:6:2 Not found
Happy Day:Mary Ann:12.99:197:101 Not found
Harry:Potter Not found
asd:dsa Not found
Harry:Potter Not found
而不是我想要的:
Harry:Potter found
Harry:Potter found
我不太确定是否可能是由于分隔符使用awk -f“[:]但是我不知道如何将其合并到我的代码中..
答案 0 :(得分:0)
将您的自定义标题和作者值作为变量传递给 awk
计划:
awk -F':' -v title="Harry" -v author="Potter" '$1==title && $2==author{ print $0,"found" }' file
输出:
Harry:Potter found
Harry:Potter found