Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a specific line of a file

What is the best way (better performance) to read a specific line of a file? Currently, I'm using the following command line:

head -line_number file_name | tail -1

ps.: preferentially, using shell tools.

like image 941
Jonhnny Weslley Avatar asked Sep 22 '10 00:09

Jonhnny Weslley


People also ask

How do I read the contents of a file line by line?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.

How do you read a specific line in a file C?

Solution 1 You can use fgets [^] in a loop to read a file line by line. When no more lines can be read, it will return NULL. On the first line you can use sscanf[^] to extract the integer.

How do you read a specific line in a file in shell script?

Using the head and tail Commands Let's say we want to read line X. The idea is: First, we get line 1 to X using the head command: head -n X input. Then, we pipe the result from the first step to the tail command to get the last line: head -n X input | tail -1.

Which method is used to read a single line from a file?

The readline method reads one line from the file and returns it as a string.


2 Answers

You could use sed.

# print line number 10
$ sed -n '10p' file_name
$ sed '10!d' file_name
$ sed '10q;d' file_name
like image 88
miku Avatar answered Oct 16 '22 06:10

miku


ruby -ne '$.==10 and (print; exit)' file
like image 43
ghostdog74 Avatar answered Oct 16 '22 04:10

ghostdog74