lucidguppy
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.
Most Liked
radar
I believe you can use a combination of File — Elixir v1.20.2 and Stream — Elixir v1.20.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
julismz
kumaran33
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
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









