Reputation: 11
Inside my text file, I have a list of books, that goes by title,author,price. For example,
Harry Potter - The Half Blood Prince:J.K Rowling:39.99
Title, author and price are all separated with ":" delimiter.
I have two options, search by title and/or author. An enter is read if either one is left empty.
elif [ "$title" == "" ]
then
count=`grep -c "$author" Books.txt`
echo "Found $count Records: "
awk "/$author/" Books.txt
if [ "$count" -eq 0 ]
then
echo "Book not found!"
fi
elif [ "$author" == "" ]
then
count=`grep -c "$title" Books.txt`
echo "Found $count Records: "
awk "/$title/" Books.txt
if [ "$count" -eq 0 ]
then
echo "Book not found!"
fi
There is no problem search and printing but if I invert the order, typing the author's name into the title field, I will still get the same result. What's up?
Upvotes: 0
Views: 95
Reputation: 3325
Well, you have two pieces of identical code that just checks whether a string is part of a line. If you enter the author into the title field, you end up doing this:
awk "/$title/" Books.txt
Which, when 'title' is set to the name of an author, does exactly the same thing as this (given that $author is an authors name here too):
awk "/$author/" Books.txt
To improve/make it more precise you could tell awk to count only for a given column, i.e.:
author="J.K Rowling"
awk -F ':' -v author="$author" '$2 == author' Books.txt
UPDATE
Your question is "what's up", which I have explained, but here is some kind of practical solution for you (just updating your code here):
elif [ "$title" == "" ]
then
count=$( awk -v author="$author" -F ':' '$2 == author { c++ } END { print c }' Books.txt )
if [ "$count" -eq 0 ]
then
echo "Book not found!"
else
echo "Found $count Records: "
awk -v author="$author" -F ':' '$2 == author' Books.txt
fi
elif [ "$author" == "" ]
then
count=$( awk -v title="$title" -F ':' '$2 == title { c++ } END { print c }' Books.txt )
if [ "$count" -eq 0 ]
then
echo "Book not found!"
else
echo "Found $count Records: "
awk -v title="$title" -F ':' '$2 == title' Books.txt
fi
...I haven't actually run all this code, but 'it should work' ;-)
Upvotes: 1