RSS / Atom


2016-03-10 , ,

I often find myself needing to parse a file for bits of text and piping that through to other commands but while the file has a reasonably good syntax, the structure or ordering doesn’t lend itself to just using awk. I used to reach for Perl or Ruby and bang out a one-off parser but for the past few years if I find myself writing more than a one-liner I switch to Kaz Kylheku’s TXR. It’s taking me time to grasp, mostly because I only work with it on the harder problems, but it works well.

Today I needed to fiddle with the VM’s on my workstation and couldn’t remember their IP’s. I regularly create and delete these and the IP addresses shuffle around. VMWare uses ISC DHCP as its dhcp server and I’m quite familiar with the lease file which has a series of lease declarations each with a curly-brace block containing a number of statements describing the configuration which can appear in any order. I’m only interested in a few.

Here’s a quickie script to extract what I needed:

#!/usr/bin/env txr -f
lease @{IPADDR /\d+\.\d+\.\d+\.\d+/} {@\

@/\s/client-hostname "@HOSTNAME";
@/\s/hardware ethernet @{MAC /([a-fA-F0-9][a-fA-F0-9][:\-])*([a-fA-F0-9][a-fA-F0-9])/};

Here’s the output on my workstation, which is simple to filter through other tools:

$ dhcp-leases /var/db/vmware/vmnet-dhcpd-vmnet8.leases,ubuntu,00:0c:29:96:6b:86,ross-a0cfd9724f,00:0c:29:47:ce:9a,pfSense,00:0c:29:65:5b:59,ubuntu,00:0c:29:6d:d6:b2,fbsd,00:0c:29:81:76:d6,archvm1,00:0c:29:e1:3c:3e,obsd,00:0c:29:7b:44:b3,vm1ubuntu,00:0c:29:bc:9f:39,vmdeb1,00:0c:29:34:4a:57,box,00:0c:29:1e:e8:b1,Knoppix,00:0c:29:f9:53:2b,win2kvm01,00:0c:29:8e:dd:41

Perfect! Including the shebang line at the top it’s 397 bytes.



Commenting is closed for this article.