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...
The term ____________________ refers to the practice of driving around looking for and mapping insecure WLANs.
Fill in the blank(s) with the appropriate word(s).
____ is the willingness to let people do what they wish, as long as there is no overriding justification to do otherwise.
A. Cowardice B. Tolerance C. Cultural Relativism D. Recklessness
A selected control in a report displays a blue border
Indicate whether the statement is true or false
A bar chart, sometimes called an XY chart, shows the relationship between two categories of data.
Answer the following statement true (T) or false (F)