#!/bin/bash # cgrep--grep with context display and highlighted pattern matches setglobal context = '0' setglobal esc = '"^['" setglobal boldon = ""$(esc)[1m"," boldoff = ""$(esc)[22m"" setglobal sedscript = ""/tmp/cgrep.sed.$Pid"" setglobal tempout = ""/tmp/cgrep.$Pid"" proc showMatches { setglobal matches = '0' echo "s/$pattern/$(boldon)$pattern$(boldoff)/g" > $sedscript for lineno in [$[grep -n $pattern $1 | cut -d: -f1]] { if test $context -gt 0 { setglobal prev = "$shExpr(' $lineno - $context ')" if test $prev -lt 1 { # This results in "invalid usage of line address 0". setglobal prev = '"1'" } setglobal next = "$shExpr(' $lineno + $context ')" if test $matches -gt 0 { echo "$(prev)i\\" >> $sedscript echo "----" >> $sedscript } echo "$(prev),$(next)p" >> $sedscript } else { echo "$(lineno)p" >> $sedscript } setglobal matches = "$shExpr(' $matches + 1 ')" } if test $matches -gt 0 { sed -n -f $sedscript $1 | uniq | more } } trap "$[which rm] -f $tempout $sedscript" EXIT if test -z $1 { echo "Usage: $0 [-c X] pattern {filename}" > !2; exit 0 } if test $1 = "-c" { setglobal context = $2 shift; shift } elif test $[echo $1|cut -c1-2] = "-c" { setglobal context = $[echo $1 | cut -c3-] shift } setglobal pattern = $1; shift if test $Argc -gt 0 {for filename in @Argv { echo "----- $filename -----" showMatches $filename } } else { cat - > $tempout # Save stream to a temp file. showMatches $tempout } exit 0