Recursive regular experession substitution

I found the following script very useful a lot of time. It can recursively substitute regexp passed as first argument whith the second one. The core of the script is the chstr_ric function:

function chstr_ric () {

  echo -e "Num par: $#\n$0\n$1\n$2\n$3\n"

# se non è specificata la dir di partenza parto da quella attuale
  if [ -z "$3" ]; then
    DIR=$PWD
  else
    DIR=$3
  fi

# Entro nella dir
  echo -e "directory root: $DIR\n"
  cd $DIR

  for FILE in * ; do
    if [ -d $FILE ] ; then
      echo -e "\n*************\nEntro dentro a: $DIR/$FILE\n*************"
# Se è una dir ci entro dentro e chiamo la ricorsione
      cd $FILE
      chstr_ric "$1" "$2" "$FILE"
      echo -e "\n*************\nEsco da a: $DIR/$FILE\n*************"
# finita la ricorsione risalgo nell albero delle directory
      cd ..
    else
      echo -e "\tProcesso il file: $FILE"
# se è un file attuo la sostituzione
      sed -e "s/$1/$2/g" $FILE > $FILE.newsed
      mv -f $FILE.newsed $FILE
    fi
  done
}

It checks the third parameter, and if it's present it's considered like the starting directory. If not, actual directory is set as the root. After that is scans all the files and:

  • If it finds a file it starts the substitution using sed and a temporary file
  • If it finds a directory, then it calls himself recursively using the third parameter
The script is downloadable here.

Leave a comment