Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a particular line from a file

Tags:

Is it possible to extract a particular line from a file knowing its line number? For example, just get the contents of line N as a string from file "text.txt"?

like image 551
Skizit Avatar asked Oct 25 '10 12:10

Skizit


People also ask

How do you go to a specific line in a file?

To do this, press Esc , type the line number, and then press Shift-g . If you press Esc and then Shift-g without specifying a line number, it will take you to the last line in the file. To look for the next occurrence after the first, either press n or press / again and then press Enter .

How do I get lines from a file?

Using “wc -l” There are several ways to count lines in a file. But one of the easiest and widely used way is to use “wc -l”. The wc utility displays the number of lines, words, and bytes contained in each input file, or standard input (if no file is specified) to the standard output.

How do I grep a specific line from a file?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.


2 Answers

You could get it by index from readlines.

line = IO.readlines("file.txt")[42] 

Only use this if it's a small file.

like image 152
Jonas Elfström Avatar answered Sep 20 '22 04:09

Jonas Elfström


Try one of these two solutions:

file = File.open "file.txt"  #1 solution would eat a lot of RAM p [*file][n-1]  #2 solution would not n.times{ file.gets } p $_  file.close 
like image 29
Nakilon Avatar answered Sep 22 '22 04:09

Nakilon