In a bash script I am working on I need to add a grep option to be accepted at the command line to only read words from a file that match a pattern. The user is prompted to enter books, authors, publishers, and publish years, and the list is stored in a file books in book1~author1~pub1~date1 format, with each set on a separate line. If "print" is passed at the command line (bookinfo print), the file "books" content is put in a book_print file in Book: book1 (\n) Author: author1 ect. format. What I am trying to do is add a grep option so that when a string is specified at the command line with the -f option, only lines in the "books" file that include that pattern are put in the "book_print" file. For example, if the command is "bookinfo -f "author2"", only lines in "books" that include author2 will be put in the book_print file. (bookinfo is the name of the script)
Here is what I have so far. I started the -f option code but don't know where to go from here.
#!/bin/bash
n=${1:-1}
#while getopts f name
#do
# case $name in
# f)dopt=1;;
# *) echo "Invalid arg";;
# esac
#done
if [[ $1 == "print" ]]
then
printf "Booktitle: \t\t %s\n" `awk -F '~' '{print $1}' books` >> book_print
printf "Author(s): \t\t %s\n" `awk -F '~' '{print $2}' books` >> book_print
printf "Publisher: \t\t %s\n" `awk -F '~' '{print $3}' books` >> book_print
printf "Year of Publication: \t %s\n" `awk -F '~' '{print $4}' books` >> book_print
else
for ((i = 1; i < n + 1; i++))
do
echo -n "Booktitle: "
read b
book=$b
echo -n $book >> books
echo -n "~" >> books
echo -n "Author(s): "
read a
author=$a
echo -n $author >> books
echo -n "~" >> books
echo -n "Publisher: "
read p
publisher=$p
echo -n $publisher >> books
echo -n "~" >> books
echo -n "Year of publication: "
read y
year=$y
echo $year >> books
done
fi
EDIT - I changed the while loop code to the following:
while getops ":f" opt;
do
case $opt in
f)
grep "$OPTARG" books
;;
*)
echo "Invalid argument."
;;
esac
done
My books file contains the lines A~B~C~D and E~F~G~H. When I run the command ./bookinfo -f "A", I am shown the entire books file rather than just the line that contains A.