SpruceTips
SpruceTips

Reputation: 225

Replacing string in file with perl

I have a list of about 10 servers that I would like to change a string in all 10 servers.

I have written a script that looks at the file and with a loop and should use perl -i -pe to change the line /opt/nimsoft/bin/niminit "" "start" to #/opt/nimsoft/bin/niminit "" "start" (add a # to comment out)

oldstring = /opt/nimsoft/bin/niminit "" "start"

newstring = #/opt/nimsoft/bin/niminit "" "start"

I am having trouble escaping the /, I have tried \ and \Q and \E. Any ideas?

  for i in `cat $file`
  do

    echo "Disable application on startup"

     oldstring=start /opt/nimsoft/bin/niminit "" "start"
     newstring=#start /opt/nimsoft/bin/niminit "" "start"
    ssh -t $i sudo perl -p -i -e 's/oldstring/newstring/g' /etc/rc.tcpip
    #  /etc/rc.tcpip:start /opt/nimsoft/bin/niminit "" "start"
    echo "==============================================="
  done

Upvotes: 1

Views: 100

Answers (2)

Miller
Miller

Reputation: 35198

If you use s{}{} instead of s///, you won't have to worry about escaping the forward slashes.

The following adds a comment before the string that you wanted to match if it isn't already commented:

perl -i -pe 's{(?<!#)(?=start /opt/nimsoft/bin/niminit "" "start")}{#}' /etc/rc.tcpip

Upvotes: 1

Phil Perry
Phil Perry

Reputation: 2130

Perl will permit the use of delimiters other than /. You might try ~ or { } pairs. Also, sed might be easier to use than a Perl script.

Upvotes: 0

Related Questions