LouisL
LouisL

Reputation: 121

Shell scripting- using user input variable with wildcard

I got this text file that I need to read in for my program with user input:

Harry Potter - The Half Blood Prince:J.K Rowling

The little Red Riding Hood:Dan Lin

Harry Potter - The Phoniex:J.K Rowling

Harry Potter - The Deathly Hollow:Dan Lin

Below is a snippet of my code:

#search with both field entered 
elif [ -n "${SearchTitle}" ] && [ -n "${SearchAuthor}" ]; then
    echo "Found ` grep -icw "${SearchTitle}" $FILENAME | grep -icw "${SearchAuthor}" $FILENAME ` record(s) :"
    cat $FILENAME | grep -iw "${SearchTitle}" $FILENAME | grep -iw "${SearchAuthor}" $FILENAME | awk -F':' '{ printf "%-1s, %-1s, $%-1s, %-1s, %s\n", $1, $2, $3, $4, $5 }'
fi

The user will input the title & author when prompted and they will see how many copies found and list the whole line.

The user can input only "harry" and "Dan" and should be able to list out the output too.

However, when doing so.. both little red riding hood and harry potter deathly hollow appears.

How do I rectify this problem so that it will only match the single line?

How can I use wildcard with user input variables?

Upvotes: 0

Views: 321

Answers (2)

Barmar
Barmar

Reputation: 781141

You're piping to grep, but you're also specifying a filename argument; when it gets a filename, it doesn't read from the pipe, so you're just getting the output of both greps independently instead of feeding one into the next.

elif [ -n "${SearchTitle}" ] && [ -n "${SearchAuthor}" ]; then
    echo "Found ` grep -iw "${SearchTitle}" "$FILENAME" | grep -icw "${SearchAuthor}" ` record(s) :"
    grep -iw "${SearchTitle}" "$FILENAME" | grep -iw "${SearchAuthor}" | awk -F':' '{ printf "%-1s, %-1s, $%-1s, %-1s, %s\n", $1, $2, $3, $4, $5 }'
fi

Upvotes: 3

Elliott Frisch
Elliott Frisch

Reputation: 201447

The main issue you have is the shell will "glob" your input. You can prevent that by using quotes. For example(s), consider ls * and ls "*". So, use "$FILENAME"

Upvotes: 0

Related Questions