Korn Shell: Unix and Linux Programming Manual, Third Edition, The By Anatole Olczak
Table of Contents
Appendix D. Sample Korn Shell Scripts
Searching for Patterns in Files - kgrep
This is the Korn shell version of the Unix grep command. The b option is not supported, and the i flag causes multi-character expressions to be matched in both all upper-case or all lower-case (kgrep i AbC test matches AbC, abc, or ABC in test, but not aBc or other permutations). Here are the supported options:
c
display the number of lines that contain the given pattern
i
ignore case of letters during comparison (see above)
l
display only names of files with matching lines once
n
display the output with line numbers
s
do not display error messages
v
display all lines, except those that match the given expression
#!/bin/ksh## kgrep - Korn Shell grep program## Declare default flagsCFLAG= IFLAG= LFLAG= NFLAG= SFLAG= VFLAG=integer LNUM=0 COUNT=0 TOT_COUNT=0# Disable file name generationset -f# Check usageif (($# < 2))thenprint "Usage: $0 [options] expression files"exit 1fi# Parse command-line optionswhile truedocase $1 in-b* ) print "b option not supported" ;;-c* ) CFLAG=1 ;;-i* ) IFLAG=1 ;;-l* ) LFLAG=1 ;;-n* ) NFLAG=1 ;;-s* ) SFLAG=1 ;;-v* ) VFLAG=1 ;;-* ) print "$0: unknown flag $1"exit 2 ;;* ) PATTERN=$1shiftbreak ;;esacshiftdone# Set no-print flagsNOPRINT=$VFLAG$CFLAG$LFLAGV_NOPRINT=$CFLAG$LFLAG# Set upper/lower patterntypeset -u UCPATTERN=$PATTERNtypeset -l LCPATTERN=$PATTERN# Check for file argif (($# == 0))thenprint "Must have file argument"exit 1fi# Process filesfor FILEdo# Open file for standard inputexec 0<$FILE# Read each line in filewhile read -r LINEdo# Increment line number counter((LNUM+=1))# Check each line for the patterncase $LINE in# See if PATTERN matches input*$PATTERN*)if [[ $VFLAG = "" ]]then[[ $NOPRINT = "" ]] && \print -r "${NFLAG:+$LNUM:}$LINE"((COUNT+=1))fi ;;# For -i option: See if# upper/lowercase patterns match*$UCPATTERN* | *$LCPATTERN*)if [[ $IFLAG != "" ]]thenif [[ $VFLAG = "" ]]then[[ $NOPRINT = "" ]] && \print -r "${NFLAG:+$LNUM:}$LINE"((COUNT+=1))fielseif [[ $VFLAG != "" ]]then[[ $V_NOPRINT = "" ]] && \print -r "${NFLAG:+$LNUM:}$LINE"((COUNT+=1))fifi ;;# For -v option: See if# pattern doesn't match!(*$PATTERN*))if [[ $VFLAG != "" ]]then[[ $V_NOPRINT = "" ]] && \print -r "${NFLAG:+$LNUM:}$LINE"((COUNT+=1))fi ;;esacdone# Process -l flag# Display just the filename# if there are matches in this fileif [[ $LFLAG != "" ]] && ((COUNT))thenprint - $FILEfi# Increment the total match counter# for when kgrep'ing multiple files((TOT_COUNT+=COUNT))# Reset the line number counter for the next fileLNUM=0# Reset the match counter for the next fileCOUNT=0done# Process -c flag# Display the total number of matches found[[ $CFLAG != "" ]] && print $TOT_COUNT# Exit successfullyexit 0