zoukankan      html  css  js  c++  java
  • Lua 遍历Linux目录下的文件夹

    代码如下,里面有注释,应该能看懂。

    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, "([^
    
    ]+.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,
    ", "0,
    ");
        --替换后的字符串写入到文件。以前的内容会清空
        writeFile(line, new)
        start_pos = end_pos + 1
    end
  • 相关阅读:
    Linux调整时区和同步时间
    wget命令
    apt-get损坏修复
    apt-get卸载命令
    apt-get命令
    ps命令
    卸载Ambari
    YARN Registry DNS启动提示“53端口被占用”错误的解决方法
    反转链表,时间复杂度O(n),空间复杂度O(1)
    简易版之最短距离
  • 原文地址:https://www.cnblogs.com/wliangde/p/3907748.html
Copyright © 2011-2022 走看看