Shashikant shah

Wednesday, 26 November 2014

How to replace particular word in a file

#!/bin/bash

echo -n "Enter File Name :- "
read name

echo -n "Enter File Path :- "
read path

file=`echo $path$name` > /dev/null

if [[ ! -f "$file" ]];then

        echo "'$file' Please Check Path & File Name..!"
exit 2
fi

echo -n "Enter Replace Word :- "
read old

E=`grep -oh "\W*\w*$old\w*\W*" $file | head -1 && grep -oh "\W*\w*$old\w*\W*" $file | sort -n | grep -w $old | head -1`

echo -n $E > /tmp/a

s=`grep -oh "\W*\w*$old\w*\W*" /tmp/a | sort | head -1`

if [[ "$old" != $s ]];then

        echo "'$old' Word is not Found in file."
exit 3
else

echo -n "Enter New Word :-  "
read new
f=`cp -r $file $file.old`
        echo "backup is created"

for runtime in 1 2 3 4 5
do
E=`sed -i "s/\(^\| \ .\)$old\( \|$\)/$new /g" $file | sed -i "s/\(.^\| \)$old\( \|$\)/ $new /g" $file`
done
echo "File has been replaces"
exit 0
fi

No comments:

Post a Comment