[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: search/replace with regexp



"Ben-Nes Michael" <miki@canaan.co.il> writes:

> Any one know about good search/replace (text) that accept regexp as pattern
> ?

Off-line. i.e. script-based? I will be happy to learn a new
tool. FWIW, up to now, I used a simple wrapper for ed:

#!/bin/bash

tmp_script=/tmp/subst.ed.$$

PROGNAME=$(basename $0)

usage () {
echo "

Usage:  $PROGNAME [ -h ] regexp substitute files

Does a global search of the (ed-style) regexp and
performs the substitution in place (overwrites!)
for every file listed.

Options:
   -h    prints this usage message.

" 1>&2
}

while getopts h OPTION
do
case $OPTION in
    h) usage
       exit 1
       ;;
    \?) echo '$PROGNAME: unknown option $OPTARG'
        usage
	exit 2
	;;
esac
done
shift $(expr $OPTIND - 1)

if [ $# -lt 3 ]; then
   echo "$PROGNAME: Wrong number of arguments"
   exit 3
fi

regexp=$1
substitute=$2
shift 2

echo "g/$regexp/s//$substitute/g
w
q
" > $tmp_script

for file in "$@"
do
   if [ -f $file ]
      then echo -n "Making substitution in file $file ... " 
           orig_version=/tmp/subst.$(basename $file).$$
	   cp -f $file $orig_version
           ed -s $file < $tmp_script 
	   if [ $? -eq 0 ]
              then rm -f $orig_version
                   echo "done"
              else mv -f $orig_version $file
                   echo "error in ed ... aborted"
           fi
      else echo "File $file does not exist"
   fi
done

rm -f $tmp_script

##############################################################

For an important warranty note, see the copyright section of man
chat(8) :).

-- 
Oleg Goldshmidt | ogoldshmidt@NOSPAM.computer.org 
If it ain't broken, it hasn't got enough features yet.

=================================================================
To unsubscribe, send mail to linux-il-request@linux.org.il with
the word "unsubscribe" in the message body, e.g., run the command
echo unsubscribe | mail linux-il-request@linux.org.il