function add_new_book

Use and complete the template provided. The entire template must be completed. If you don't, your post may be deleted!

  1. The problem statement, all variables and given/known data:
    What i want to do is to ensure that the Book added is not already existing book in the record. I believe my logic is correct cause as long as the user do not in put space for any of the field the code work fine=.=
    E.g He enter Harry for Title instate of Harry Potter
    He enter J for author instate of J.K Rowling

  2. Relevant commands, code, scripts, algorithms:

  3. The attempts at a solution (include all code and scripts):

function add_new_book
{
    echo "1) add_new_book"
    echo "Title: "
    read title
    echo "Author: "
    read author
    c1=`grep -w $title BookDB.txt |grep -w $author|wc -l` #cannot work when got space 
if [ $c1 -ne 0 ]
then
    echo "Price: "
    read price
    echo "Qty Available: "
    read qtyA
    echo "Qty Sold: "
    read qtyS
    echo "$title:$author:$price:$qtyA:$qtyS" >> BookDB.txt
    echo "New book title "$title" added successfully!"
else
   echo " Name not Found"
fi
  1. Complete Name of School (University), City (State), Country, Name of Professor, and Course Number (Link to Course):
    University of Wollongong CSCI212 conducted by Mr Tian

Note: Without school/professor/course information, you will be banned if you post here! You must complete the entire template (not just parts of it).

c1=`grep -w $title BookDB.txt |grep -w $author|wc -l` #cannot work when got space

Give the sample contents of BookDB.txt

and you can use grep -c for counting ( instead of wc -l)

1 Like

$title expands to whatever the value of it was. So, how would you grep a file for a string with spaces in it? With quotes of course -- in this case, use double quotes because single quotes makes variables act as plaintext (e.g., $title will be literally $title instead of 'Harry').

1 Like

c1=`grep -w $title BookDB.txt |grep -w $author|wc -l` #cannot work with space