0

My php file has some defined variables with $downtime_hosts, what i need is a single command to just find and replace entire $downtime_hosts = 8; into $downtime_hosts = 15; and without affecting the other $downtime_hosts used several time within the file.

here my number 8,15,16 may change anytime, what i need is find the line beginning with$downtime_hosts = anyinteger and simply replace with my new line $downtime_hosts = newinteger . please note anyinteger / newinteger=2,3,4,15or any

$downtime_hosts = 8;

$total_hosts = $all_hosts - $downtime_hosts;

if ($host_up == $total_hosts )

Hosts under downtime $downtime_hosts `

Any inputs are really welcomed !

0

1 Answer 1

4
sed 's/$downtime_hosts = 8;/$downtime_hosts = 15;/' file.php

The $ poses no problem since it won't act as an anchor unless it's found at the end of the pattern. The sed script does need to be single-quoted though a the shell otherwise would try to expand $downtime_hosts as a shell variable.

To only match the pattern in the beginning of a line:

sed 's/^$downtime_hosts = 8;/$downtime_hosts = 15;/' file.php

If the integer 8 could be any integer:

sed 's/^$downtime_hosts = [0-9]*;/$downtime_hosts = 15;/' file.php

To replace the integer with an integer held by a shell variable $newint:

sed "s/^\$downtime_hosts = [0-9]*;/\$downtime_hosts = $newint;/" file.php

Notice that we now have to use double quotes around the sed editing script for the shell to expand the $newint variable. This also means that we are forced to escape the two existing $ from the shell.

8
  • Why doesn't it require ^ as i was looking for just the line that contains from the beginning, the whole time i was trying using this.. but it just an stupidity i was trying .. can you elaborate a little more about it my dear friend.
    – Kunal Saha
    Commented Jan 21, 2017 at 20:13
  • @KunalSaha If you require the match to be anchored to the beginning of the line (this was not specified in the question), then yes, you should add ^ to the beginning of the pattern.
    – Kusalananda
    Commented Jan 21, 2017 at 20:15
  • here my number 8,15,16 may change anytime, what i need is find the line beginning with` $downtime_hosts = anyineger` and simply replace with my new line $downtime_hosts = newinteger . please note anyinteger / newinteger=2,3,4,15 or any.
    – Kunal Saha
    Commented Jan 21, 2017 at 20:36
  • @KunalSaha Are you going to have lines starting with $downtime_hosts that will not have "= integer" but something else, i.e an expression? Commented Jan 21, 2017 at 20:41
  • 2
    @KunalSaha You are aware that you are continuing to change the question? This was not what you asked. I will however update my answer, because I'm a nice guy.
    – Kusalananda
    Commented Jan 21, 2017 at 20:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .