Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crystal get from n line to n line from a file

Tags:

crystal-lang

How can I get specific lines in a file and add it to array?

For example: I want to get lines 200-300 and put them inside an array. And while at that count the total line in the file. The file can be quite big.

like image 238
Eman Avatar asked Mar 05 '23 19:03

Eman


2 Answers

File.each_line is a good reference for this:

lines = [] of String
index = 0
range = 200..300

File.each_line(file, chomp: true) do |line|
  index += 1
  if range.includes?(index) 
    lines << line
  end
end

Now lines holds the lines in range and index is the number of total lines in the file.

like image 105
Johannes Müller Avatar answered Mar 17 '23 03:03

Johannes Müller


To prevent reading the entire file and allocating a new array for all of its content, you can use File.each_line iterator:

lines = [] of String

File.each_line(file, chomp: true).with_index(1) do |line, idx|
  case idx
  when 1...200  then next          # ommit lines before line 200 (note exclusive range)
  when 200..300 then lines << line # collect lines 200-300
  else break                       # early break, to be efficient
  end
end
like image 28
WPeN2Ic850EU Avatar answered Mar 17 '23 01:03

WPeN2Ic850EU