#!/bin/bash # # Syntax: grepem [-h] [-v] [-w] [-u] regexp [file [...]] # # Purpose: Performs a grep on the given files and opens those that match # the given regular expression regexp. # If only one input argument is specified, the grep is performed # on all files in the current directory. # If the option -w is specified, grepem searches for string as a # word. # By default grepem does a case-insensitive grep. However, if the # option -u is specified, grepem distinguishes between upper # and lower case letters. # By default emacs is used to open the files, unless the -v flag # is present; in that case vi is used. # Created: Jul 31, 2007 by Bart De Schutter # Last revised: Aug 6, 2007 by Bart De Schutter # # See http://www.deschutter.info/util/scripts.html for the latest version of # this script. # Status: public # Category: files # # Process input arguments. # editor="emacs" case_string="-i" word_string="" while getopts :hvwu option do case "$option" in h) sed '/^$/q;/^#!/d;s/^# //;s/^#//' $0 >&2 exit 1 ;; v) editor="vi";; w) word_string="-w";; u) case_string="";; \?) echo >&2 echo >&2 "Unknown option: $OPTARG" echo >&2 sed '/^$/q;/^#!/d;s/^# //;s/^#//' $0 >&2 exit 1 ;; esac done shift $(($OPTIND-1)) if [ $# -eq 0 ]; then echo >&2 echo >&2 "ERROR: ${0##*/} requires at least 1 input argument." echo >&2 sed '/^$/q;/^#!/d;s/^# //;s/^#//' $0 >&2 exit 1 fi # # Perform grep and open files that match the given regexp. # if [ $# -eq 1 ]; then lst=$(grep -l $case_string $word_string "$1" *) else lst=$(grep -l $case_string $word_string "$@") fi if [ ! -z "$lst" ] then # Do some processing in order to be able to deal with files that # contain a space or a # in their name. lst=$(echo "$lst" | sed -e 's/ /\\ /g;s/#/\\#/g' | tr "\n" " " ) eval $editor $lst else echo "No files found that match the given regular expression." fi