Write a shell program called wgrep that searches a file for a given pattern, just as grep does. For each line in the file that matches, print a "window" around the matching line. That is, print the line preceding the match, the matching line, and the line following the match. Be sure to properly handle the special cases where the pattern matches the first line of the file and where the pattern matches the last line of the file.
What will be an ideal response?
#!/bin/sh
# wgrep - a wrapped to grep that includes an 'n' line window
# around the matching line
window=1
matches=1
if [ "$1" = "-w" ] ; then
if [ $2 -le 0 -o $2 -gt 5 ] ; then
echo "$0: context window $2 is an invalid size (range is 1..5)"
exit 1
fi
window=$2
shift 2
fi
pattern="$1"
file="$2"
# now let's get the line numbers of all matching lines
for match in $( grep -n "$pattern" "$file" | cut -d: -f1 )
do
before=$(( $match - $window ))
after=$(( $match + window ))
if [ $matches -eq 1 ] ; then
echo "------------"
matches=$(( $matches + 1 ))
fi
sed -n "${before},${after}p" $file
echo "------------"
done
exit 0
You might also like to view...
Which of the following is a touch input device?
A) Joystick B) Stylus C) Microphone D) Webcam
When working with SQL, if a field includes an aggregate function, you need to use a ________ clause, which specifies the aggregated field criteria and restricts the results based on aggregated values
Fill in the blank(s) with correct word