代碼如下,里面有注釋,應該能看懂。
function getFile(file_name) local f = assert(io.open(file_name, 'r')) local string = f:read("*all") f:close() return string end function writeFile(file_name,string) local f = assert(io.open(file_name, 'w')) f:write(string) f:close() end --從命令行獲取參數, 如果有參數則遍歷指定目錄,沒有參數遍歷當前目錄 if arg[1] ~= nil then cmd = "ls "..arg[1] else cmd = "ls" end print("cmd", cmd) --io.popen 返回的是一個FILE,跟c里面的popen一樣 local s = io.popen(cmd) local fileLists = s:read("*all") print(fileLists) while true do --從文件列表里一行一行的獲取文件名 _,end_pos, line = string.find(fileLists, "([^\n\r]+.txt)", start_pos) if not end_pos then break end -- print ("wld", line) local str = getFile(line) --把每一行的末尾 1, 替換為 0, local new =string.gsub(str, "1,\n", "0,\n"); --替換后的字符串寫入到文件。以前的內容會清空 writeFile(line, new) start_pos = end_pos + 1 end
