您当前的位置: 首页 > 

ITKEY_

暂无认证

  • 0浏览

    0关注

    732博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

lua读取文本并去掉重复行

ITKEY_ 发布时间:2021-09-22 19:18:17 ,浏览量:0

需求

有一个文本文件,里面有大量的重复行,要求把重复的部分去掉.我本想用我的老本行java来实现的.感觉挺简单的,拿lua练一下手吧!

源文本如下:

column XH format a9
column XM format a9
column XB format a4
column XH format a9
column XM format a9

只要是前半部分是一样的(如:column XH format ),就认为是重复的,保留一行就行. 结果应该是:

column XM format a9
column XH format a9
column XB format a4
代码

-- http://lua-users.org/wiki/FileInputOutput

-- 判断文件是否存在
function file_exists(file)
  local f = io.open(file, "rb")
  if f then
    f:close()
  end
  return f ~= nil
end

-- 获取文本的所有行,如果文件不存在行,返回一个空的table
function lines_from(file)
  if not file_exists(file) then
    return {}
  end
  lines = {}
  for line in io.lines(file) do
    lines[#lines + 1] = line
  end
  return lines
end

-- 测试代码是否正常
--local file = "file.lua"
local file = "/home/vncuser/.wp/oracle/test.sql"
local lines = lines_from(file)
local dicLines = {}
local resultLines = {}
for k, v in pairs(lines) do
  --打印行号 + 内容
  --print("line[" .. k .. "]", v)
  --截取前面,保存起来用于查询是否重复
  local index, _ = string.find(v, "format")
  local qz = string.sub(v, 0, index - 2)
  if not dicLines[qz] then
    resultLines[#resultLines + 1] = v
  end
  dicLines[qz] = true
end
--输出结果到文件
--覆盖写入模式
file = io.open("/home/vncuser/.wp/oracle/test_result.sql", "w")

local str = table.concat(resultLines, "\n")
-- appends a word test to the last line of the file
file:write(str)
-- closes the open file
file:close()

关注
打赏
1665243900
查看更多评论
立即登录/注册

微信扫码登录

0.0370s