0

I have a multi-part grep in place that is extracting lines from router config files. The grep pulls a variety of fields that occur only once in the file, such as IP address, logging status, snmp community, etc. For this, I have a simple grep such as the following:

grep -e "ip address" -e "logging status" -e "snmp community" $file

However, I also need it to pull the first instance of a field that occurs several times in the file, in this case, the "ospf area" field. With a single grep, I can accomplish this via:

grep -m 1 "ospf area" $file

How can I perform both functions in a single grep? I'm looping over hundreds of very long files, and I'd like to keep this as efficient as possible. I'm also not married to grep for this, so I'd be interested in seeing other ideas.

1 Answer 1

3

Perhaps awk would be a better tool for this. We can remember which ones we've printed and not print them again with something along the lines of:

awk '/ip address/ {print} /logging status/ {print} /snmp community/ {print} /ospf area/ {if(!ospf[$0]++) {print}}' "$file"

which will print every line that matches any of your first examples from grep (and each is done separately in case you want only the first, otherwise you can combine them with |). For lines matching ospf area we build an array of all the lines we have already seen, and only print it if we haven't seen this line before.

This will print each unique ospf area line as written. If you only want the first ospf area line and not any others you could just change setting the array to setting an int/flag:

awk '/ip address|logging status|snmp community/ {print} /ospf area/ {if(!ospf++) {print}}' "$file"

and if you don't want to handle anything different about the other lines, we can simplify using the fact that awk's default action is to print the matching line:

awk '/ospf area/ {if(!ospf++) {print}} /ip address|logging status|snmp community/' "$file"

You must log in to answer this question.

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