2

An example from (the excellent) Unix Programming Environment considers an address book:

 John Perkins 616-555-4444
 Bill Jotto 773-222-1112
 Dial-a-Clown 738-224-5823
 Prince Alex 837-999-999
 Pizza Hut 833-339-222
 Pizza Puk 882-922-222
 Pizza Buk 822-221-111

now I am writing a program that searches this address book called '411'

   grep $* /file/location/411

now running 411 will yield

 $> 411 John
 >John Perkins 616-555-4444

now say I want to call John and invite him for some pizza (So I am searching for John number and Pizza numbers).

 $>411 John Pizza
 grep: can't open pizza

No match!

So how to I tell the shell to accept multiple argument with arbitrary spaces?

2
  • 1
    When you wrote $>411 John Perkins Pizza did you mean $>411 John Pizza? Otherwise both Perkins and Pizza should have generated errors. Commented May 13, 2012 at 22:26
  • That's true.. I shall edit. Thanks. Commented May 13, 2012 at 22:50

1 Answer 1

3

When you call grep with more than one argument, it assumes the first is the pattern and all others are the files to be searched. You'll need to make two modifications:

  1. When you call your program, you'll need to enclose multi-word arguments in double-quote characters. This is standard shell behavior.

  2. Your program will need to read the arguments from the command line and either send them individually to grep or build a compound expression (arg1|arg2|arg3) and pass it to grep with the -E (extended regex) flag.

For example:

args="$1"
shift   # $2 becomes $1, $3 becomes $2, and so on
while [ -n "$1" ]; do
   args="$args|$1"
   shift
done

grep -E "$args" /path/to/address/book

Or:

while [ -n "$1" ]; do
  grep "$1" /path/to/address/book
  shift
done
Sign up to request clarification or add additional context in comments.

4 Comments

What if I want an arbitrary number of arguments?
Cool! The funny thing is the review loops right in the next section and I just didn't make the connection. Thanks a lot.
"standard linux behavior". You probably mean "standard shell behaviour". Linux doesn't care what shell you use, or how or if that shell processes arguments.
Shouldn't that be uppercase -E, or explicitly call egrep?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.