码迷,mamicode.com
首页 > 其他好文 > 详细

Erlang正则解析操作文件

时间:2014-06-08 10:38:23      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:erlang 正则   erlang操作文件   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").

解析的文件如下:

bubuko.com,布布扣

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

              (2)erlang的file:get_cwd(),file:list_dir("."),默认的是工作目录或是c:cd(...)后进入的目录,如果没有设定erlang的工作目录,则“.”表示当前目录;

               (3)学习erlang中正则表达式的使用方法

Erlang正则解析操作文件,布布扣,bubuko.com

Erlang正则解析操作文件

标签:erlang 正则   erlang操作文件   erlang获取文件路径   

原文地址:http://blog.csdn.net/zcc_0015/article/details/28706931

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!