replace.sh
Poor man’s replace in files. Get it. Or see it…
#!/bin/bash## Thu May 12 12:02:01 CEST 2005 * Miguel de Benito <nonick AT 8027 DOT org>## Poor man's "replace in files"...#################### Load lib#if [ ! -f ~/bin/messages.sh ]; thenecho "~/bin/messages.sh is required but not found. Bye..."exit 1fi. ~/bin/messages.shTMPPATH="/tmp/replace"################### Check params#if (( ${#@} < 3 ))thenechoecho "Usage: $0 <directory> <string> <replacement> <extension>"echoecho " <string> is taken as a Perl regex"echo " <replacement> must have any $ escaped"echo " <extension> is optional"exit 1fiDIR=$1STR=$2REP=$3EXT=$4if [ ! -d "$DIR" ]thenerror_msg "Either '$DIR' is not a directory or it is not readable."exit 2fi# Replace . with working directory[ "$DIR" == "." ] && DIR=$(pwd)if [ -z "$EXT" ]thenEXT='*'extmsg="every file"elseextmsg="'$EXT' files"fi################### Go#echoecho "Replacing '$STR' with '$REP' in $extmsg of directory '$DIR':"echorun_cmd "Creating temporary directory... " "/bin/mkdir -p $TMPPATH/$DIR"files=$(find $1 -maxdepth 1 -name "*$EXT")[ -z "$files" ] && info_msg "No files match the extension pattern" && exit 0;for file in $filesdolines=$(grep -clP "$STR" $file)if [ ! -z "$lines" ]thenecho " $file"name=$(basename $file)tmp=$TMPPATH/$name~~cat $file | perl -ne "s/$STR/$REP/; print $_;" > $tmpcp $tmp $DIR/$namefidone# TODO: check return codes and ask if we should revert changes- Download this code: replace.sh


November 27th, 20075:09 am at
Programming Tutorials
I couldn’t understand some parts of this article, but it sounds interesting