#!/bin/csh -f
# "greps" for phrases (several words) which may be split across a line
# break, i.e., a 2 line phrase.  Actually the phrase could be any
# regular expression. (The line break should be treated as a space when
# composing the regular expression.)
# You can invoke this program as grep2lp, egrep2lp, or fgrep2lp in order
# to get the regular expression syntax and options of grep, egrep, or
# fgrep, respectively.  But any options must appear in the first
# argument.  After the argument with options if any, the first argument
# is the phrase to look for; remember to quote spaces.  The remaining
# arguments are files to look in.

set prog = $0
set prog = $prog:t

set opts
if ("$1" =~ -*) then
  set opts = $1
  shift
endif

set noclobber
set tmpfiles

foreach file ($argv[2-])
  set numlines = `cat $file | wc -l`
  set tempfile = $file.$prog.$$
  awk '{if (NR != 1) print $0; \
        if (NR != '$numlines') printf "%s%s", $0, " "}' $file > $tempfile
  if (! $status) set tmpfiles = "$tmpfiles $tempfile"
end

if ($#argv>1) then
  if ("$tmpfiles" != "") then
    `echo $prog | cut -d2 -f1` $opts "$1" $tmpfiles \
      | sed 's+\([^:]\{1,\}\).'$prog.$$':+\1:+'
    rm $tmpfiles
  endif
else
  set tempfile = /tmp/$prog.$$
  set numlines = `cat | tee $tempfile | wc -l`
  cat $tempfile | awk '{if (NR != 1) print $0; \
                        if (NR != '$numlines') printf "%s%s", $0, " "}' \
    | `echo $prog | cut -d2 -f1` $opts "$1"
  rm $tempfile
endif
