Skip to content

Instantly share code, notes, and snippets.

@mlankenau
Last active March 12, 2020 11:17
Show Gist options
  • Save mlankenau/784e8bc2e0a7ba1050715e68a03e5303 to your computer and use it in GitHub Desktop.
Save mlankenau/784e8bc2e0a7ba1050715e68a03e5303 to your computer and use it in GitHub Desktop.
defmodule TextFileUtils do
def fix_line_breaks(file_path) do
{:ok, file} = File.open(file_path)
out_file_path = "/tmp/fixed_file_#{:erlang.system_time}.tmp"
{:ok, out_file} = File.open(out_file_path, [:write])
process_file(file, out_file, "")
File.close(file)
File.close(out_file)
out_file_path
end
defp process_file(in_file, out_file, last) do
c = IO.read(in_file, 1)
case {last, c} do
{"\r", "\n"} ->
#windows case
IO.write(out_file, "\n")
{"\r", _} ->
# weird osx excel case, only \r
IO.write(out_file, "\n")
IO.write(out_file, c)
{_, "\n" = c} ->
# unix case, only newline
IO.write(out_file, "\n")
{_, "\r" = c} ->
# we skip it
{_, :eof} ->
nil
{_, c} ->
IO.write(out_file, c)
end
if c != :eof do
process_file(in_file, out_file, c)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment