首页 > 解决方案 > 如何在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 本机实现?

标签: lua

解决方案


for line in io.lines"output.txt" do
   local var1, var2 = line:match"(%S*)%s*(.*)"
   print(var1)
   print(var2)
end

推荐阅读