lua - 如何在lua中使用2列迭代和打印文本?
问题描述
为了演示,我得到了以下名为 output.txt 的文本文件,其中包含以下简单数据:
/etc/csf/csf.deny Hello this is abc
/var/lib/csf/csf.tempip Hello this is CSF
/var/lib/csf/csf.tempban That is nice you got tempban here!
/root/blocked_ips.txt blocked ip is not great
我想将第一列存储为 var1,将列的其余部分存储为 var2。由于我熟悉 bash,因此我可以使用 bash 中的以下代码来实现这一点:
#!/bin/bash
output="output.txt"
var1=$(awk '{ print $1 }' $output)
var2=$(awk '{$1=""; $0=$0; $1=$1; print}' $output)
while read -r var1 var2; do
echo "Var1: $var1 , Var2: $var2"
# -- Now I can use var1 and var2 to do something else in this loop
done <"$output"
此 bash 脚本的输出:
[root]# ./test
Var1: /etc/csf/csf.deny , Var2: Hello this is abc
Var1: /var/lib/csf/csf.tempip , Var2: Hello this is CSF
Var1: /var/lib/csf/csf.tempban , Var2: That is nice you got tempban here!
Var1: /root/blocked_ips.txt , Var2: blocked ip is not great
我可以popen
在 lua 脚本(来自 bash 脚本的包装器)中使用来实现这一点,但是是否有 lua 本机实现?
解决方案
for line in io.lines"output.txt" do
local var1, var2 = line:match"(%S*)%s*(.*)"
print(var1)
print(var2)
end
推荐阅读
- java - 通过身份验证标头并将其添加到下一个请求
- python - 就地替换适用于对象但不适用于字符串 dtype
- javascript - 在 a 中居中文本防止移动
- java - 如何在 Spring Boot 中测试调用另一个 SOAP Web 服务的 REST Web 服务
- html - 制作固定宽度和高度的html
- node.js - 部署响应到 github
- arrays - TypeScript - 防止只有接口实现的对象推送到对象类实例数组
- c++ - 在模板类的声明和定义分离的情况下防止重新定义问题
- c++ - 在 C++ 中使用 MinGW 工具包含多个类/.o 文件
- flutter - 如何将 RaisedButton 移动到屏幕的底部中心?