问题描述
在Lua中寻找替换以下命令的解决方案:
Looking for solution to replace following command in 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看起来像这样
/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
推荐答案
在Lua中,这是一个函数,如果将整个文件内容传递给它,它将打印所需的值:
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
请参见 Lua演示
使用 string.gmatch(text,"[^ \ r \ n] +")
,访问每个文件行(根据需要调整),然后主要部分是m,n = string.match(line,"^dhcp%-range[^,]*,([^,]+),([^,]+)")
实例化 m
(第一个IP)和 n
(第二个IP)在以 dhcp-range
开头的行中找到.
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模式详细信息:
-
^
-字符串的开头 -
dhcp%-range
-文字字符串dhcp-range
(-
是Lua中的匹配0个或多个匹配项的量词,但是 越少越好,并且要匹配文字 -
[^,] *,
-0 +个除,
以外的字符,然后是,
-
([[^,] +)
-组1(m
):除,
以外的一个或多个字符 -
,
-逗号 -
([[^,] +)
-组1(n
):除,
以外的一个或多个字符.
-
,必须对其进行转义.正则表达式转义由%
组成.^
- start of stringdhcp%-range
- a literal stringdhcp-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,
.
这篇关于a在文件中搜索字符串并打印第二列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!