i have a file which contains some block of lines like -

define host {
use linux-box
host_name node001
alias node001
address 192.168.36.133
}

define host {
use linux-box
host_name node002
alias node002
address 192.168.73.19
}

can anyone help me in getting a script which takes <node001> and <192.168.36.133> as search criteria search in the file and delete the block that matches the search

Member Avatar for sravan953

I didn't understand one thing! Can you please elaborate a bit?

I didn't understand one thing! Can you please elaborate a bit?

Thanks Sravan for looking the query

I have a file with some data in the format specified below:

define host {
use linux-box
host_name node001
alias node001
address 192.168.36.133
}

Like this there are soo many blocks specific to particular node and ip. The variable here will be <node> and <ip>.

I am trying to write a script which will take this <ip> and <node> as input and will search my file for a match and if found, it should delete that particular block from the file.

You could do something along the lines of this:

# Open our input (hosts) file
file_in = open(filename)
# Open a temporary output file
file_out = open(fileoutname, 'w')
# host_found will tell us if we found the line define host {
host_found = False
# Now iterate over each line in the hosts file
for line in file_in:
    if host_found:
        # If we found the proper host, we won't write to output
        # but we'll want to monitor for the closing bracket to know
        # when to stop skipping lines
        if line.strip() == '}':
            host_found = False
    else:
        if line.strip() == 'define %s {' % host_ip:
            # we found the first line
            host_found = True
        else:
            # copy each line to output (except the ones we want to skip)
            file_out.write(line)

Then all you'll need to do is rename your temporary outfile to the same path and name as the hosts file.

Break the file into groups that start with the "define host" record

So, you want to append each record to a list, but first:

If "define host" is found in the record then send the list to a function to process it (test for 'nod3001' and/or the IP address, and write to a file if that's what you want to do with this group).

Re-define the list as empty, i.e. ready for the next group.

Now append the record to the list

Finally, you will have to process the last list as there was no next record with "define host" to process it.

If you want further help, post the code as you have it so far, and we can help with that. The general rule is that words get answered with words and code gets answered with code. Sorry, but there are too way many people who want freeprograms.com to even consider writing code from scratch.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.