问题
I'm very new to BASH Shell programming. Here's my issue, I need to split data from my file (with a semicolon delimiter) and search if a certain book exists.
file contents:
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
My code here:
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
when I run my code, it gives me:
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
instead of what I want:
Harry:Potter found
Harry:Potter found
I'm not so sure if it might be due to the delimter to use awk -f "[:] but I'm don't know how to incorporate into my code..
回答1:
Pass your custom title and author values as a variables to awk
program:
awk -F':' -v title="Harry" -v author="Potter" '$1==title && $2==author{ print $0,"found" }' file
The output:
Harry:Potter found
Harry:Potter found
来源:https://stackoverflow.com/questions/48490532/bash-shell-using-awk-with-a-delimiter-2-search-terms