Tuesday, October 4, 2022

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

Issue

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.


Solution

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.



Answered By - nu11p01n73R
Answer Checked By - Willingham (WPSolving Volunteer)