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
radar
2
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
Update:
String.strip/1 is deprecated. Use String.trim/1 instead.
2 Likes