Ubuntu使用Lua批量转换文件编码格式为UTF-8

/ linux / 0 条评论 / 2362浏览

批量将目标文件夹下指定文件类型(例如js,htm,php)转换成为utf-8的编码格式。以解决windows开发 拿到linux系统开发出现乱码的问题。


简要使用说明

names=getpathes("/opt/lampp/htdocs-wmsay/wmsay/template/comeing_city_c8/")

修改此行,变成你需要转换的文件夹地址

if getExtension(path)=="php" or getExtension(path)=="htm" or getExtension(path)=="js"

修改此行,可指定需要转换的文件类型

代码

require "io"  
require "lfs" 


function getpathes(rootpath, pathes)  
    pathes = pathes or {}
    for entry in lfs.dir(rootpath) do
        if entry ~= '.' and entry ~= '..' then  
            local path = rootpath .. '/' .. entry  
            local attr = lfs.attributes(path)
            assert(type(attr) == 'table')
              if(attr ~= nil) then
            if attr.mode == 'directory' then
                getpathes(path, pathes)
            else  
               if getExtension(path)=="php" or getExtension(path)=="htm" or getExtension(path)=="js" then
                  table.insert(pathes, path)
               end
            end 
            end 
        end 
    end  
    return pathes  
end  

function getExtension(str)  
    return str:match(".+%.(%w+)$")  
end  

names={}
names=getpathes("/opt/lampp/htdocs-wmsay/wmsay/template/comeing_city_c8/")
for i,v in ipairs(names) do
  print("changging "..v)
   gm="enca -L zh_CN -x UTF-8 "..v
   os.execute(gm);
end

使用方法

  1. 将上面的代码保存为xxx.lua (我的命名成了convert2utf8.lua)
  2. lua convert2utf8.lua

遇到问题:module 'lfs' not found

解决方法: 安装

sudo apt install luarocks

之后安装lfs

luarocks install luafilesystem

遇到问题:sh: enca: 未找到命令

解决方法:

sudo apt install enca

运行结果

请输入图片描述

至此完美解决批量转换指定类型的文件的编码格式转换问题