#!/bin/sh

#phrase - search for words across lines
# $1 == search string; remaining args == filename

#hacked from sed & awk green book.

#BUG: The last line may contain a non-match. I don't know why

search=$1
shift

if [ "$#" -gt 0 ] ; then
    file=$1
else
    file=/dev/stdin
fi

while :
do
	sed '
/'"$search"'/b
N
h
s/.*\n//
/'"$search"'/b
g
s/ *\n/ /
/'"$search"'/{
g
b
}
g
D' "$file" | ( \
         if [ "$file" = /dev/stdin ] ; then
              cat
         else
              while read i ; do
                  echo "$file: $i"
              done
         fi ; )
    shift
    [ "$#" -eq 0 ] && break
    file=$1
done
