Search code examples
erlangappendfile-readfile-search

Erlang - search for a specific string within an external file and append file if not present


I want to check if a specific string is present in a external file,by reading the file line by line using erlang. If the specific string is not present ,I wish to append the file with the string. So far I have managed to open the file and read the file contents line by line. but i have no idea how to proceed with the rest. I am new to erlang so any help on this question will be highly appreciated.

What I have tried so far:

-module(helloworld). 
-export([readlines/1,get_all_lines/1,start/0]). 

readlines(FileName) ->
    {ok, Device} = file:open(FileName, [read]),
    try get_all_lines(Device)
      after file:close(Device)
    end.

get_all_lines(Device) ->
    case io:get_line(Device, "") of
        eof  -> [];
        Line -> Line ++ get_all_lines(Device)
    end.



start() ->
    

readlines("D:\\documents\\file.txt"),
Txt=file:read_file("D:\\documents\\file.txt"),
io:fwrite("~p~n", [Txt]).



What I got as the result:

helloworld:start(). {ok,<<"hello\r\nhi">>} ok

The sample file that I am using : file name:"file.txt"

file contents: hello hi


Solution

  • If you need try find specific text in file you can try use re:run/2 function. Here is example how you can try find specific string in file and if you don't find this string - the string will be will be recorded in log.txt file:

    -module(helloworld).
    -export([start/0]).
    
    -define(LOG_FILE, "log.txt").
    
    start() ->
      read_data("file.txt").
    
    read_data(FileName) ->
      case file:read_file(FileName) of
        {error, enoent} ->
          io:format("File ~p not found~n", [FileName]);
        {ok, Data} ->
          find_text(Data)
      end.
    
    find_text(Data) ->
      Text = <<"specific string">>,
      case re:run(Data, Text) of
        nomatch ->
          write_log(Text);
        _ ->
          ok
      end.
    
    write_log(Text) ->
      case file:read_file(?LOG_FILE) of
        {ok, Data} when Data =/= <<>> ->
          file:write_file(?LOG_FILE, <<Data/binary, "\n", Text/binary>>);
        _ ->
          file:write_file(?LOG_FILE, Text)
      end.