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


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.


I believe you can use a combination of!/3 and

I’m on my phone now, so I don’t know if this code will work for sure, but here goes:!("file.txt")
|> Stream.with_index

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.txt") 
|> Stream.with_index
|> ({line, index}) -> IO.puts "#{index + 1} #{line}" end)
10 Likes!(“inputfile.txt”)
|> Stream.with_index
|> {line, i} -> IO.puts “#{i+1} #{line}” end)
|> Stream.into(!(“output.txt”))

1 Like