Tuesday 27 May 2014

python string replace

Lets say we have a file, where we have hosts name and there true and false status. We checked the health status of the health and found we need to make it false, if its true, because of the health check is failing: how to do this:


bash: sed -i 's/true \(host1.*\)/false \1/g' 

bash: to print file from line 5 to 10:
 sed -n '5,10p' filename

file example:
true host1.example.com
true host2.example.com



cat true-false.py
#! /usr/bin/env python

myfile = open('haproxy-file.txt')
for line in myfile:
  if 'host1' in line:
    print (line.replace('true','false'))



# How I will do inline of a file and update the file?, with the new value.

#! /usr/bin/env python

myfile = open('haproxy-file.txt')
for line in myfile:
  if 'host1' in line:
    UpdateLine = line.replace('true','false')
    MyWriteFile = open('haproxy-file.txt','r+')
    MyWriteFile.write(UpdateLine)
    MyWriteFile.close()



In the above script, still some error are there: [will fix and update. ]

what is the error:
# Output:
false host1.example.com
rue host2.example.com #-> NOTE: 't' is missing over here

# Expecting Output:
false host1.example.com
true host2.example.com

No comments:

Post a Comment