Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua. Search string in a file and print second column

Tags:

regex

lua

Looking for solution to replace following command in Lua:

grep "dhcp-range" /tmp/etc/dnsmasq.conf | awk -F "\"*,\"*" '{print $2}'

tried

for line in file:lines() do
        if line:match("([^;]*),([^;]*),([^;]*),([^;]*),([^;]*)") then
                print(line[2])
        end
end

and it doesnt work.

/tmp/etc/dnsmasq.conf looks like this

dhcp-leasefile=/tmp/dhcp.leases
resolv-file=/tmp/resolv.conf.auto
addn-hosts=/tmp/hosts
conf-dir=/tmp/dnsmasq.d
stop-dns-rebind
rebind-localhost-ok
dhcp-broadcast=tag:needs-broadcast

dhcp-range=lan,192.168.34.165,192.168.34.179,255.255.255.0,12h
no-dhcp-interface=eth0
like image 803
Murad Avatar asked Oct 26 '25 05:10

Murad


1 Answers

Here is a function in Lua that will print the values you need if you pass the whole file contents to it:

function getmatches(text)
    for line in string.gmatch(text, "[^\r\n]+") do
        m,n = string.match(line,"^dhcp%-range[^,]*,([^,]+),([^,]+)")
        if m ~= nil then 
            print(m,n) 
        end
    end
end

See Lua demo

With string.gmatch(text, "[^\r\n]+"), each file line is accessed (adjust as you see fit), and then the main part is m,n = string.match(line,"^dhcp%-range[^,]*,([^,]+),([^,]+)") that instantiates m with the first IP and n with the second IP found on a line that starts with dhcp-range.

Lua pattern details:

  • ^ - start of string
  • dhcp%-range - a literal string dhcp-range (a - is a quantifier in Lua matching 0 or more occurrences, but as few as possible, and to match a literal -, it must be escaped. Regex escapes are formed with %.)
  • [^,]*, - 0+ chars other than , and then a ,
  • ([^,]+) - Group 1 (m): one or more chars other than ,
  • , - a comma
  • ([^,]+) - Group 1 (n): one or more chars other than ,.
like image 141
Wiktor Stribiżew Avatar answered Oct 28 '25 20:10

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!