Lua. 在文件中查找字符串并打印第二列

寻找用 Lua 替换以下命令的解决方案:

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

尝试了以下代码:

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

但它无法工作。

/tmp/etc/dnsmasq.conf 文件看起来像这样:

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
点赞
用户107090
用户107090

尝试这段代码:

for line in io.lines() do
    local a,b=line:match("^dhcp%-range=.-,(.-),(.-),")
    if a~=nil then
        print(a,b)
    end
end

这个模式读取的是:在行的开头匹配 dhcp-range=(注意在 Lua 中需要转义 -),跳过下一个逗号之前的所有内容,并捕获两个逗号之间的下两个字段。

2017-06-18 21:41:54
用户3832970
用户3832970

以下是一个 Lua 函数,如果您将整个文件内容传递给它,它将打印您需要的值:

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

参见Lua演示

使用 string.gmatch(text, "[^\r\n]+"),可以访问每个文件行(根据需要进行调整),然后主要部分是 m,n = string.match(line,"^dhcp%-range[^,]*,([^,]+),([^,]+)"),它将 mn 实例化为以 dhcp-range 开头的行上发现的第一个 IP 和第二个 IP。

Lua模式详细信息

  • ^ - 字符串的开头
  • dhcp%-range - 一个文本字符串 dhcp-range- 是Qaquantifier,用于匹配0或多个,但尽可能少的出现,并且为了匹配一个字面上的-,它必须被转义。正则表达式转义使用 %。)
  • [^,]*, - 除,以外的0个或多个字符,然后是,
  • ([^,]+) - 组1 (m):除,以外的一个或多个字符
  • , - 逗号
  • ([^,]+) - 组1 (n):除,以外的一个或多个字符。
2017-06-18 21:44:31