• Erlang正则解析操作文件


    -module(tool).
    %% ====================================================================
    %% API functions
    %% ====================================================================
    -export([modify_hostname/0,modify_ip/0]).
    modify_hostname() ->
     {ok,HostName} = inet:gethostname(),
     %通过截取和加入。得到priv所在的文件夹
     EbinDir = filename:dirname(code:which(?MODULE)),
     ProjectDir = string:sub_string(EbinDir,1,length(EbinDir)-4),
     PrivDir = ProjectDir ++ "priv/",
     {ok,Files} = file:list_dir(PrivDir),
     lists:foreach(fun(A)-> replace(PrivDir++A,HostName) end,Files),
     io:format("modify hostname successfully!~n").
    replace(FileName,HostName) ->
     {ok,Content} = file:read_file(FileName),
     RawString = binary_to_list(Content),
    %%  以非贪婪模式匹配@开头不包括}的随意字符同一时候以逗号结束的特征串
     {ok,MP1} = re:compile("@[^}]*,",[ungreedy]),
     ResultString1 = re:replace(RawString,MP1,"@"++HostName++",",[{return,list},global]),
    %%  以非贪婪模式匹配@开头不包括}和逗号的随意字符同一时候以]}结束的特征串
     {ok,MP2} = re:compile("@[^},]*]}",[ungreedy]),
     ResultString2 = re:replace(ResultString1,MP2,"@"++HostName++"]},",[{return,list},global]),
    %%  以非贪婪模式匹配@开头不包括}和逗号的随意字符同一时候以]}结束的特征串
     {ok,MP3} = re:compile("@[^,]*}]",[ungreedy]),
     ResultString3 = re:replace(ResultString2,MP3,"@"++HostName++"}]",[{return,list},global]),
        file:write_file(FileName, list_to_binary(ResultString3)).

    modify_ip() ->
     {ok,Iflist} = inet:getif(),
     {A,B,C,D} = element(1,lists:nth(2,Iflist)),
     Ebin = filename:dirname(code:which(?MODULE)),
    %%  得到nodefinder.app所在的路径
     ProjectDir = string:sub_string(Ebin,1,length(Ebin)-17),
     AppDir = ProjectDir ++ "Res/ebin/nodefinder.app",
     {ok,Content} = file:read_file(AppDir),
     LocalIp = "{"++integer_to_list(A)++","++integer_to_list(B)++","++integer_to_list(C)++","++integer_to_list(D)++"}",
     RawString = binary_to_list(Content),
    %%  通过正則表達式进行匹配后。然后替换成本机Ip
     {ok,MP} = re:compile("{[0-9]+,[0-9]+,[0-9]+,[0-9]+}"),
     ResultString = re:replace(RawString, MP, LocalIp,[{return,list}]),
     file:write_file(AppDir,list_to_binary(ResultString)),
     io:format("modify ip successfully!~n").

    解析的文件例如以下:

    总结:(1)学习通过filename:dirname(code:which(?MOUDLE))获取文件所在的绝对路径。

                  (2)erlang的file:get_cwd(),file:list_dir("."),默认的是工作文件夹或是c:cd(...)后进入的文件夹,假设没有设定erlang的工作文件夹。则“.”表示当前文件夹;

                   (3)学习erlang中正則表達式的用法

  • 相关阅读:
    Day11作业
    day12作业
    samba共享服务
    PHP7 redis扩展安装
    linux lin命令
    PhpStorm,Pycharm,Goland破解
    PHP规范PSR2
    PHP 过滤器(Filter)
    Linux下Redis的安装与配置
    linux命令汇总
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/9996961.html
Copyright © 2020-2023  润新知