Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read n-th line from a text file in bash?

Tags:

file

linux

bash

Say I have a text file called "demo.txt" who looks like this:

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Now I want to read a certain line, say line 2, with a command which will look something like this:

Line2 = read 2 "demo.txt"

So when I'll print it:

echo "$Line2"

I'll get:

5 6 7 8

I know how to use 'sed' command in order to print a n-th line from a file, but not how to read it. I also know the 'read' command but dont know how to use it in order a certain line.

Thanks in advance for the help.

like image 427
user3206874 Avatar asked Nov 21 '14 08:11

user3206874


People also ask

How do I read a text file line by line in bash?

The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line: while read -r line; do COMMAND; done < input. file.

How do I read a line from a text file in Linux?

Using the head and tail Commands 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.


1 Answers

Using head and tail

$ head -2 inputFile | tail -1
5 6 7 8

OR

a generalized version

$ line=2
$ head -"$line" input | tail -1
5 6 7 8

Using sed

$ sed -n '2 p' input
5 6 7 8
$  sed -n "$line p" input
5 6 7 8

What it does?

  • -n suppresses normal printing of pattern space.

  • '2 p' specifies the line number, 2 or ($line for more general), p commands to print the current patternspace

  • input input file

Edit

To get the output to some variable use some command substitution techniques.

$ content=`sed -n "$line p" input`
$ echo $content
5 6 7 8

OR

$ content=$(sed -n "$line p" input)
$ echo $content
5 6 7 8

To obtain the output to a bash array

$ content= ( $(sed -n "$line p" input) )
$ echo ${content[0]}
5
$ echo ${content[1]}
6

Using awk

Perhaps an awk solution might look like

$  awk -v line=$line 'NR==line' input
5 6 7 8

Thanks to Fredrik Pihl for the suggestion.

like image 196
nu11p01n73R Avatar answered Oct 10 '22 02:10

nu11p01n73R