Navigation


RSS / Atom



TXR

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
@(collect)
lease @{IPADDR /\d+\.\d+\.\d+\.\d+/} {@\

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

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

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

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

Comment


Comment

Commenting is closed for this article.