2

I have two files: master.tbl and sites.lst

The file master.tbl is a list of sites, with their port configurations, port names, IP addresses, etc. There are lines containing site descriptions, comments, etc., but they are irrelevant. The lines containing the site configurations are arranged thusly, and are delimited by spaces.:

{server} {SITE NAME} {port name} {configuration flags}

The port names consist of the site name in lowercase, a dash, a "P", and the port number.

Example:

server01 HAWAII23-USR hawaii23-P1 blah-configuration-blah-arguments
server01 HAWAII23-ADM hawaii23-P2 blah-configuration-blah-arguments
server01 HAWAII23-ADM hawaii23-P3 blah-configuration-blah-arguments
server01 HAWAII23-USR hawaii23-P4 blah-configuration-blah-arguments

sites.lst is a list of sites that I need to search the master.tbl file for.

I need to comment out (insert a # at the beginning of the line), and extract the server name and port name (into a file named stoplist.lst) of every line that meets ALL of the following criteria:

  1. contains any site name listed in sites.lst
  2. contains "-ADM "
  3. has a port number higher than '2' (example: hawaii23-P3)

In the above example, the master.tbl file would look like this:

server01 HAWAII23-USR hawaii23-P1 blah-configuration-blah-arguments
server01 HAWAII23-ADM hawaii23-P2 blah-configuration-blah-arguments
#server01 HAWAII23-ADM hawaii23-P3 blah-configuration-blah-arguments
server01 HAWAII23-USR hawaii23-P4 blah-configuration-blah-arguments

...and stoplist.lst would contain (assuming HAWAII23 is in sites.lst):

server01 hawaii23-P3

master.lst is almost 300,000 lines, so doing this manually would be...bad.

1

Here's an awk solution:

awk 'NR==FNR{z[$0"-ADM"]++;next}
{p=$3;sub(/.*-P/, "", p); if ($2 in z && p > 2)
{print $1,$3 > "stoplist.lst"; $0="#"$0}}1' sites.lst master.tbl

This reads sites.lst first and sets $0"-ADM" (that is the site name + the string -ADM) as an index of the array z. It then processes master.tbl extracting the value after -P in the 3rd field as p and, if the conditions are met (2nd field is in z and p greater than 2) it prints 1st and 3rd fields to stoplist.lst and comments the line out.
Note that it doesn't edit the file in-place but you can always redirect to another file and overwrite the original if everything is OK (though with a recent gnu awk you have the option -i inplace).

  • This worked beautifully. Thank you so much. – Chris Boone May 24 '16 at 19:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.