B
Bulhac Mihai
how can i read only a line from a txt file?
for example i want to read only line 3
for example i want to read only line 3
2007/9/7 said:how can i read only a line from a txt file?
for example i want to read only line 3
how can i read only a line from a txt file?
for example i want to read only line 3
2007/9/7 said:how can i read only a line from a txt file?
for example i want to read only line 3
From: Bulhac Mihai [mailto:[email protected]]
# how can i read only a line from a txt file?
# for example i want to read only line 3
if you want a ready-made solution (written in ruby, of course), you can use rio.
irb(main):005:0> require 'rio'
=> true
# get first 4 lines (as always in ruby indexing starts at 0)
irb(main):006:0> rio('test.txt').lines[0..3]
=> ["1testing \n", "2testing \n", "3asdfasdf\n", "\n"]
# get first lines 4 to 6
irb(main):007:0> rio('test.txt').lines[3..5] # a range of lines
=> ["\n", "4asdf\n", "[]\n"]
# thus, reading line 3 would be
irb(main):013:0> rio('test.txt').lines[2..2]
=> ["3asdfasdf\n"]
kind regards -botp
2007/9/7 said:From: Bulhac Mihai [mailto:[email protected]]
# how can i read only a line from a txt file?
# for example i want to read only line 3
if you want a ready-made solution (written in ruby, of course), you can= use rio.
irb(main):005:0> require 'rio'
=3D> true
# get first 4 lines (as always in ruby indexing starts at 0)
irb(main):006:0> rio('test.txt').lines[0..3]
=3D> ["1testing \n", "2testing \n", "3asdfasdf\n", "\n"]
# get first lines 4 to 6
irb(main):007:0> rio('test.txt').lines[3..5] # a range of lines
=3D> ["\n", "4asdf\n", "[]\n"]
# thus, reading line 3 would be
irb(main):013:0> rio('test.txt').lines[2..2]
=3D> ["3asdfasdf\n"]
kind regards -botp
Or even
rio('test.txt').line[2]
sed -ne '3 p' your_file
robert
2007/9/7 said:awk "3==NR" your_file
When I think about it, this is probably more efficient for large files
and low line numbers:
head -3 your_file | tail -1
awk "3==NR{print;exit}" your_file
The rule is: never use anything other than awk unless
you have to.
line_three = File.readlines(the_file)[2]
From: rio4ruby [mailto:[email protected]]
# Or even
# rio('test.txt').line[2]
thanks. i just wanted (and hoped) that the op will try his hands on rio and experiment it.
rio has simple solutions for line grabbing, like eg, "get line 3..5, lines 100,200,300..400, and lines containing /test/"
rio('test.txt').line[3..5,100,200,300..400,/test/]
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.