LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   String replace in shell script (https://www.linuxquestions.org/questions/programming-9/string-replace-in-shell-script-883120/)

jnreddy 05-27-2011 07:39 PM

String replace in shell script
 
Hi Friends and Guru's

I need to replace a string in my script..

my sample file :

root# cat passwd
################################
This is script generated file

tftp = off
dns = off

my script:
#!/bin/sh
cat /nir/passwd | grep tftp >/dev/null
RC=$?
if [ "$RC" = 0 ] ; then
echo "Tftp is exist"
RM=`cat /nir/passwd | grep tftp | awk '{print$3}'`

if [ $RM = off ] ; then


echo "Fail: TFTP is : $RM: Do you want to make it : ON"
else
echo " TFTP is | ON......exiting"
fi
fi

in my sample its showing tftp = off and it should to modified to tftp = on.

any help is appreciateable

Thanks In Advance
JNReddy

dwhitney67 05-27-2011 10:12 PM

Here's one solution... the answer you seek is in bold text.

Code:

#!/bin/bash

FILE=passwd

state=`grep tftp $FILE | awk '{print $3}'`

if [ "$state" == "" ]; then
        echo "Error; TFTP not defined in $FILE"
        exit 1

elif [ "$state" == "off" ]; then
        echo -n "Do you want to enable TFTP (y/n)? [y] "
        read ans

        if [ "$ans" == "" -o "$ans" == "y" ]; then
                sed -e "s/tftp = off/tftp = on/" -i $FILE
                echo "TFTP has been turned ON."
        else
                echo "TFTP will be left OFF... exiting"
        fi

elif [ "$state" == "on" ]; then
        echo -n "Do you want to disable TFTP (y/n)? [y] "
        read ans

        if [ "$ans" == "" -o "$ans" == "y" ]; then
                sed -e "s/tftp = on/tftp = off/" -i $FILE
                echo "TFTP has been turned OFF."
        else
                echo "TFTP will be left ON... exiting"
        fi

else
        echo "TFTP is neither ON or OFF... exiting"
        exit 1
fi

exit 0


jnreddy 05-28-2011 01:20 AM

Hats off
 
Hi dwhitney67,


Thanks a Lot it's an excellent script, it solved my task....

Thanks a lot...


Thanks
JNReddy

grail 05-28-2011 02:07 AM

Please mark as SOLVED once you have a solution


All times are GMT -5. The time now is 03:42 AM.