0

My .txt file contains these kind of content :

The Law and Lawyers of Pickwick, by Frank Lockwood                 21214
Frankenstein, by Mary Wollstonecraft                               20

The first string is book name,second is author and the last one is book number. I want to print the whole line when someone search with the author name.I tried using grep.

#!/bin/bash
BOOKFILE="/home/sk/GUTINDEX.ALL"
author=$1
if [[ -z "$author" ]]; then 
echo -n "Author name : "
read author
fi
grep $author $BOOKFILE

If I run this and search for Frank Lockwood it prints both the lines.But I want to print the line when the entire input string match(both the first name and last name)

1 Answers1

0

You should change it to this:

#!/bin/bash
BOOKFILE="/home/sk/GUTINDEX.ALL"
author=$@
if [[ -z "$author" ]]; then 
    read -rp "Author name: " author
fi
grep "$author" "$BOOKFILE"

If you run it as:

$ ./script Frank Lockwood

You are setting positional parameter 1 to Frank and parameter 2 to Lockwood. Parameter 2 is not in use in your script. $@ is an array that will represent all positional parameters.

Also if you are to allow read to set your author variable to a string with whitespace it will fail on the grep line without quoting author.

jesse_b
  • 37,005