首页 > 解决方案 > 在 Lua 脚本上运行 sed 命令

问题描述

我需要在 Lua 脚本上运行这个 sed 命令:

sed -i "1i sameText" log.txt

我无法将 var(日志文件名)发送到 Lua 脚本上的 sed。

我愿意:

local datafile = log.txt

local date = os.date("%d-%m-%Y,%H:%M:%S")

os.execute('sed -i "1i date,sameText" datafile')

错误sed: no input files

标签: sedlua

解决方案


First, datafile should be a string-- not the "txt" field of a probably nonexistent log object.

An easy way to embed variables in Lua strings is to use string.format:

local datafile = 'log.txt'
local date = os.date("%d-%m-%Y,%H:%M:%S")
local cmd = string.format('sed -i "1i %s,sameText" "%s"', date, datafile)
local r = os.execute(cmd)

If you just want to insert text at the beginning of a file, you can also do that in Lua directly without requiring sed:

local function prependToFile(filename, txt)
    local hnd = io.open(filename, "rb")
    local s = hnd:read "*a"
    hnd:close()

    local hnd = io.open(filename, "wb")
    hnd:write(txt, "\n", s)
    hnd:close()
end

local datafile = 'log.txt'
local date = os.date("%d-%m-%Y,%H:%M:%S")
prependToFile(datafile, date .. ",sameText")

推荐阅读