我对 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 "[:] 的分隔符造成的,但我不知道如何合并到我的代码中。
通过您的定制title and author值作为变量awk
程序:
awk -F':' -v title="Harry" -v author="Potter" '$1==title && $2==author{ print $0,"found" }' file
输出:
Harry:Potter found
Harry:Potter found
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)