Friday, April 29, 2016

The Occasional sed, and other ways to solve problems

I find myself wanting to find things in text files, and rely upon the computer to get things right, rather than me spotting trends.  Sometimes I'll get close enough and then brute force the rest, but it's not 'the right way'.

Case in point:
I wanted to find a list of every feature set my NXOS boxes use.

Given:
All of my configs are in a standard directory


I can "grep feature *.cfg" and get a list-  but it comes out like this:

switchname.cfg:feature XXX
switchname2.cfg:feature XXX
switchname3.cfg:feature XXX

I can't pump it into "sort -u" which will uniqueify the list, because the filename was appended to the front of each line.

so my initial thought was to just trim off everything up to the : then sort on that, and I ended up down this rabbit hole:


grep ^feature *rt* | sed 's/\(^.*cfg:\)\(.*$\)/\2/' | sort -u  | more

this:
s/  starts the substitute pattern
 \( escape slash, and paren starts a catpure
^ matches beginning of line
.* matches everything
cfg:  search terminates on this
\) escape slash, and close parent to stop the capture

\( escape slash, and paren starts a capture
.*$ matches everything until the end of the line
\) escape slash, and close paren to end the capture

/ starts the replacement stanza
\2 specifies printing out the second capture group-  in essence, throwing everything in the line up to .cfg: away
/' end of the replacement stanza
| sort -u     sorts, and uniquifies it.






Of course, an easier way to do this was just:
grep -h 
prints out matches without prepending filename, and then I can just do the sort -u, and be done with it.

there's a lot of ways to skin a cat, and some are way more obvious than others.