There is a requirement to find and replace a string from file’s in the in the directory name across all the files and directories in the given directory.

We already know some basic commands like mv,sed/perl & find commands . We will use these basic commands to write a script and get the expected result .

basic commands 

mv
mv ABC DEF  -> to rename a directory
find
find /dir -type f -exec grep -l "ABC" {} \; | xargs perl -pi -e 's/ABC/DEF/g' 
Above command is used find and replace ABC in all the files with DEF on /dir 
sed
sed 's/ABC/DEF/g' -->To replace a string in a word 
perl
perl -pi -e 's#ABC#DEF#g' file --> this searches and replaces ABC to DEF .

We combine this in to 2 scenarison .

  1. To find and replace the string in given file .
  2. To find and replace the string in the directy recursivley along with matched sub directory string .

On the below we have ABC directory with abc.txt and ACBC directory . Test results for both scenarios 1 and 2 given below .

Scenario 1 :

Scenario2 :

1.sh

#!/bin/bash
echo "Enter file Name"
read fileName
echo "Enter findstring "
read findstring
echo "Enter replacestring "
read replacestring
if [ -f $fileName ] ; then
 perl -pi -e 's#'$findstring'#'$replacestring'#g' $fileName
 echo "$findstring replace with $replacestring "
 else
 echo "Given file is not available "
fi

2.sh

#!/bin/bash
echo "Enter Dir Name"
read dir 
echo "Enter findstring "
read findstring
echo "Enter replacestring "
read replacestring
if [ -d $dir ] ; then
 find $dir -type f -exec grep -l "$findstring" {} \; | xargs perl -pi -e 's/'$findstring'/'$replacestring'/g' 
 echo " Word $findstring replaced with $replacestring successfully ..."
 for directory in `find $dir -type d -name "$findstring"` 
  do
    newDirName=`echo $directory |sed 's/'$findstring'/'$replacestring'/g'`
	mv $directory $newDirName
	echo " $directory name changed to $newDirName "
  done
 else
  echo "Directory not found : $dir "
fi

set -x and set +x are for debugging . Hope this article helps in detail for find and replace . ..

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *