3

When I run the below piece of code, Im not getting the expected output. Please correct me..

import socket
import re
NodeName=socket.gethostname()
change_hostname_list=['/etc/hosts1','/etc/sysconfig/network1']
for file in change_hostname_list:
        infile=open(file,'r').read()
        print NodeName
        print file
        if re.search('NodeName',file):
                print "DOOO"

I need the output "DOOO"

I'm getting the below one,

root@test06> python test.py
test06
/etc/hosts1
test06
/etc/sysconfig/network1
root@test06>
1
  • Are you sure you are not searching the wrong thing? Maybe try re.search(file, NodeName)? Commented Dec 9, 2014 at 13:34

3 Answers 3

1

replace this:

if re.search('NodeName',file):

to :

if re.search(NodeName,infile):

you don't need quote for variable, file variable is the filename from list, variable file has the content of the file.

here is the demo:

>>> import socket
>>> import re
>>> f = open('/etc/hosts')
>>> host_name =  socket.gethostname()
>>> host_name
'hackaholic'
>>> for x in f:
...     print(x)
...     if re.search(host_name,x):
...         print("found")
... 
127.0.0.1   localhost

127.0.0.1   hackaholic

found     # it founds the host name in file
# The following lines are desirable for IPv6 capable hosts

::1     localhost ip6-localhost ip6-loopback

ff02::1 ip6-allnodes

ff02::2 ip6-allrouters
Sign up to request clarification or add additional context in comments.

3 Comments

NodeName can contain special regular expression characters. Check out my answer - you may be good to go with string.find.
It worked, after changing it to infile and tried the old substring find() also.. Both worked:)
yep you are giving wrong variable name that why its was not working
1

Drop the quotes if NodeName is string it should just do string search in file.

import socket
import re
NodeName=socket.gethostname()
change_hostname_list=['/etc/hosts1','/etc/sysconfig/network1']
for file in change_hostname_list:
    infile=open(file,'r').read()
    print NodeName
    print file
    if re.search(NodeName,file):
        print "DOOO"

If you need to use some regex goodies you can concat the variable to create regular expression string and pass it to re.search.

Also, if you don't need any regular expression stuff, just plain old substring search, you can use string function find used as follows:

if file.find(NodeName):
    print "DOOO"

1 Comment

this is not going to work, its infile not file, is not about search and fine its about the variable name
0

You appear to be passing the string 'NodeName' to re.search() as a pattern instead of the variable NodeName. Remove the single quotes in line 9 of the code you provided.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.