【问题标题】:Lua. Search string in a file and print second column卢阿。在文件中搜索字符串并打印第二列
【发布时间】:2017-06-18 20:32:40
【问题描述】:

寻找在 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

【问题讨论】:

  • 请在您的问题中添加示例输入和该示例输入所需的输出。
  • [^;]* 匹配除 ; 之外的 0 个或多个字符 - 如果您的输入没有分号,为什么还要使用它?你想在 Lua 中得到什么输出?
  • 如需获取192.168.34.165,请查看ideone.com/s1U60B
  • 我想获取以“dhcp-range”开头的行并打印第二个和第三个值。分别是 192.168.34.165 和 192.168.34.179。
  • 也许ideone.com/tFzZkZ 可以吗?

标签: regex lua


【解决方案1】:

这是 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 demo

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

Lua 模式详情

  • ^ - 字符串开头
  • dhcp%-range - 文字字符串 dhcp-range- 是 Lua 中的量词匹配 0 次或多次出现,但尽可能少,并且要匹配文字 -,必须对其进行转义。形成正则表达式转义%.)
  • [^,]*, - 除了 ,, 之外的 0+ 个字符
  • ([^,]+) - 第 1 组 (m):除 , 之外的一个或多个字符
  • , - 逗号
  • ([^,]+) - 第 1 组 (n):除 , 之外的一个或多个字符。

【讨论】:

  • 完美运行。谢谢
  • 如何获取file:lines()的最后一行,请帮忙!
  • @Rainning 只需将line 分配给一个变量,在循环结束时,只会将最后一行值分配给它。
  • @WiktorStribiżew:抱歉我的不清楚。我的意思是:是否可以在没有 for 循环的情况下加快最后一行?
【解决方案2】:

试试这个代码:

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 中需要转义 -),跳过所有内容直到下一个逗号,并捕获逗号之间的接下来的两个字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 2015-10-15
    • 2012-06-21
    • 1970-01-01
    • 2017-11-17
    相关资源
    最近更新 更多