How do I read a file and enumerate its lines

I have a super simple question about elixir - how would I take a file like this

foo
bar
baz

and output a new file that enumerates the lines

1 foo
2 bar
3 baz

The examples I’ve seen so far just pass the line to a function - so I don’t know how many line’s I’ve processed so far.

5 Likes

I believe you can use a combination of https://hexdocs.pm/elixir/File.html#stream!/3 and https://hexdocs.pm/elixir/Stream.html#with_index/2

I’m on my phone now, so I don’t know if this code will work for sure, but here goes:

File.stream!("file.txt")
|> Stream.with_index
|> Stream.map(&IO.puts/1)

EDIT: got to a computer and tried that out. Not quite right – it doesn’t actually run the stream!

Here’s what I came up with which does generate the output that you want:

File.stream!("file.txt") 
|> Stream.map(&String.strip/1)
|> Stream.with_index
|> Stream.map(fn ({line, index}) -> IO.puts "#{index + 1} #{line}" end)
|> Stream.run
11 Likes

File.stream!(“inputfile.txt”)
|> Stream.with_index
|> Stream.map(fn {line, i} → IO.puts “#{i+1} #{line}” end)
|> Stream.into(File.stream!(“output.txt”))
|> Stream.run

1 Like

Update:
String.strip/1 is deprecated. Use String.trim/1 instead.

2 Likes