Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
872 views
in Technique[技术] by (71.8m points)

linux - Using shell script to replace the string in file with another string having special character

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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this

sed '0,/PIDFILE=/var/run/Naming_Service.pid/ s//PIDFILE_1234=/var/run/Naming_Service_1234.pid
PIDFILE_1235=/var/run/Naming_Service_1235.pid
PIDFILE_1236=/var/run/Naming_Service_1236.pid
 /' script > newscript
sed '0,/OPTIONS="-p ${PIDFILE}"/ s//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"
 /' newscript > script

Should output what you need.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...