Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Erlang to read a whole text file into a variable, do text replacement and write modified file to new directory

Problem: want to read content of a file (size less than 1MB) into a Erlang variable, do some text replacement and write modified contents to a new file. I am new to Erlang and want to use simple code with no error handling (use it from Erlang shell).

I have tried:

File = file:read_file("pbd4e53e0.html").

But when using

string:len(File).

I get

exception error: bad argument in function length/1 called as length({ok,<<">}) in call from string:len/1 (string.erl, line 66).

Next step is to do replacement:

re:replace(File, "<a href=\'pa", "<a href=\'../pa/pa", [{return, list}]).

Question 1: How should I read the file into an Erlang variable?

Question 2: Is the replacement ok?

like image 946
Paul Hamacher Avatar asked Jan 14 '23 19:01

Paul Hamacher


1 Answers

For the first question, file:read_file/1 returns a tuple of {Status, Result}, so the assignment should rather be like:

{ok, File} = file:read_file("pbd4e53e0.html").

Second, File will be a binary, not a string, so you need to convert it to a string first:

Content = unicode:characters_to_list(File).

(You can provide the encoding argument as well)

Then string:len(Content) will work as expected.

As for the replacements part, it's generally a very bad idea to use regex with HTML, but from the API point of view looks ok.

like image 166
bereal Avatar answered Jan 16 '23 07:01

bereal