Any Script for Finding and Replacing Text in a File?

San
Posts: 24
Joined: Sun Oct 09, 2016 2:53 pm

Any Script for Finding and Replacing Text in a File?

Postby San » Sun Oct 09, 2016 3:24 pm

Any Script for Finding and Replacing Text in a File?

sprasad
Posts: 24
Joined: Sun Oct 09, 2016 2:52 pm

Re: Any Script for Finding and Replacing Text in a File?

Postby sprasad » Sun Oct 09, 2016 3:26 pm

We encounter many situations in day today administration activity when we have to find and replace a particular word at many places in a file. This can be done using vi command manually or we can write a shell script using sed to do the task. But in case of sed we need to first make the changes in a temporary file and then rename the temporary file to original. This script eliminates the need to create a temporary file and also the find and replace can be done on multiple files at a time.


Procedure

#####################################################
#
# Purpose: This script is used to find and replace text in a file
#
#
# Author : Santosh
#
# Email : sales@s4techno.com
#
# Date : March 30, 2015
# Version : Version 1
# Script : find_replace_string.sh
#
######################################################

#Get the values from command line
findtxt=$1
replacetxt=$2
filename=$3
while test -n "$filename"
do
#Check if the file is a text file.
isAfile=`file $filename|grep text`
if test -n "$isAfile"
then
pattern=`grep $findtxt $filename`
if test -n "$pattern"
then
echo "$filename: $pattern"
echo "ed -s $filename <<CMD " >replace_string
echo "1,$ s/$findtxt/$replacetxt/g" >>replace_string
echo "w" >>replace_string
echo "q" >>replace_string
echo "CMD" >>replace_string
if test ! -x "replace_string"
then
chmod 700 replace_string
fi
./replace_string
fi
fi
found=""
found1=""
shift
filename=$3
done

Usage

$ ./find_replace_string.sh <find text> <replace text> filename

eg.

$ ./find_replace_string.sh findthis replacethis mydoc*

The above invocation will search string “findthis” and replace it with “replacethis” in files beginning with mydoc eg. mydoc1 , mydoc2, mydocument1.txt etc

It can also be used as an input to find command

$ find ./ -name “mydoc*” |xargs ./find_replace_string.sh “findthis” “replacethis”


Return to “Scripting”

Who is online

Users browsing this forum: No registered users and 1 guest