0

This question already has an answer here:

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)

marked as duplicate by Jesse_b, Community Apr 28 '18 at 16:45

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.