[SWLUG] grep question
bascule
excession at bigfoot.com
Tue Feb 12 10:13:11 UTC 2002
following some advice from telsa at the weekend i have answered my own
question by knocking up a script to do what i want...
...except that that's a lie, it took me ages! :-)
i've pasted the scrpt below, there are some obvious flaws, there is no way to
pass arguments to the internal grep command (without altering the actual
script) and no means to show a screenfull at a time, i'd welcome comments,
esp. if i've missed some obvious and easier way of doing something,
On Friday 08 February 2002 10:22 pm, you wrote:
> if i am feeding a file to grep that has an expression on each line to
> search through another file for matches, is there a way to output the line
> of the file that has the matching expression as well as the match, or to
> specify which line of the file to use as an expression?
--------begin--------
#!/bin/bash
# bgrep (bascule's grep)
# this script feeds a file with patterns to grep and returns (if exists) both
a
match from
# a second file and the pattern that matches it
# Usage: bgrep [-p] PATTERN_FILE FILE
# Search for matching expressions from file PATTERN_FILE that occur in file
FILE
#
# Options:
# -p: pause between each set of matches that is found
#
if [ $# -eq 2 ] && [ -f $1 ] && [ -f $2 ]
then
PATTERN_FILE=$1
FILE=$2
args=0
elif [ $# -eq 3 ] && [ $1 = -p ] && [ -f $2 ] && [ -f $3 ]
then
PATTERN_FILE=$2
FILE=$3
args=0
else
args=1
fi
case $args in
0)
lines=`wc -l $PATTERN_FILE|gawk '{print $1}'`
let flag=1
while [ "$flag" -le "$lines" ]
do
echo "The pattern: `echo $(head -$flag $PATTERN_FILE|tail -1)`"
echo " matches..."
grep "`echo $(head -$flag $PATTERN_FILE|tail -1)`" $FILE
if [ $? = 1 ]
then
echo " no matches found "
elif [ $1 = -p ]
then
echo "Press <Enter> to continue"
read input
fi
let flag="$flag + 1"
done
;;
1)
echo "Usage: bgrep [-p] PATTERN_FILE FILE"
echo "Search for matching expressions from file PATTERN_FILE that occur in
file
FILE"
echo ""
echo "Options:"
echo " -p: pause between each set of matches that is found"
echo ""
exit
;;
esac
---------end--------------
bascule
--
Someone's behind this. Someone wants to see a war. [...] I've got to remember
that. This isn't a war. This is a crime.
(Jingo)
More information about the Swlug
mailing list