sed - 在 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
解决方案
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")
推荐阅读
- javascript - Angular 6 - 处理多个重复的 API 调用
- javascript - 引导程序如何确定复选框/单选按钮的选中状态
- .net - ag-grid 是否支持 .netcore 上的服务器端过滤
- python - 使用 Python Pandas 将嵌套的 json 解析为 csv
- javascript - http resquest中的多个数据包
- python - 熊猫在将值设置为数据框时更改日期时间
- kubernetes - Janusgraph 部署在 kuberntes 上,存储为 Cassandra 给出错误:无法实例化配置的图
- linux - ';'的计数 在列
- oracle - Oracle 将结果集放入 FORALL 中的变量中
- c# - 没有详细信息的 Elasticsearch serilog 错误