Using shell script to replace the string in file w

2019-09-30 03:25发布

I try to replace string in the following file with another string which is having special character like(=,",-) .

This is service file , i need to customize and add Naming Service to this file restart again

#!/bin/bash

. /etc/init.d/functions

PIDFILE=/var/run/Naming_Service.pid

PORT=

OPTIONS="-p ${PIDFILE}"

RETVAL=0

prog="Naming_Service"

    start() {
        echo -n $"Starting $prog: "

        if [ $UID -ne 0 ]; then

            RETVAL=1

            failure

        else

            setsid /usr/local/bin/Naming_Service ${OPTIONS} &

            RETVAL=$?


        fi

        echo 

        return $RETVAL

    }

In this file I want to replace first occurrence of

OPTIONS="-p ${PIDFILE}"

replace with

OPTIONS_1234="-p ${PIDFILE_1234} -ORBEndpoint iiop://10.12.23.34:1234"

OPTIONS_1235="-p ${PIDFILE_1235} -ORBEndpoint iiop://10.12.23.34:1235"

OPTIONS_1236="-p ${PIDFILE_1236} -ORBEndpoint iiop://10.12.23.34:1236"

I wrote one shell script file with sed command , I have issues with special symbols. can you please give solution for this

PORT_NS=13021

PIDFILE=/home/vagrant/Naming_Service_${PORT_NS}.pid

PIDFILE_13016=/home/vagrant/Naming_Service_${PORT_NS}.pid

ORIGINAL="OPTIONS="-p ${PIDFILE}""

REPLACE="OPTIONS_13016="-p ${PIDFILE_13016} -ORBEndpoint iiop://172.31.153.56:13016""

sed -i "0,/$ORIGINAL/s//$REPLACE/" "tao"

标签: linux sed
1条回答
仙女界的扛把子
2楼-- · 2019-09-30 03:53

Try this

sed '0,/\PIDFILE=\/var\/run\/Naming_Service.pid/ s//\PIDFILE_1234=\/var\/run\/Naming_Service_1234.pid\n\PIDFILE_1235=\/var\/run\/Naming_Service_1235.pid\n\PIDFILE_1236=\/var\/run\/Naming_Service_1236.pid\n /' script > newscript
sed '0,/\OPTIONS="-p ${PIDFILE}"/ s//\OPTIONS_1234="-p ${PIDFILE_1234} -ORBEndpoint iiop:\/\/10.12.23.34:1234"\n\OPTIONS_1235="-p ${PIDFILE_1235} -ORBEndpoint iiop:\/\/10.12.23.34:1235"\n\OPTIONS_1236="-p ${PIDFILE_1236} -ORBEndpoint iiop:\/\/10.12.23.34:1236"\n /' newscript > script

Should output what you need.

查看更多
登录 后发表回答