Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read first three lines of a file in bash

Tags:

linux

bash

shell

I have the following shell script to read in the first three lines of file and print them out to screen - it is not working correctly as it prints out lines 2,3,4 instead of lines 1,2,3 - What am I doing wrong ?

exec 6< rhyme.txt

while read file <&6 ;
do
        read line1 <&6
        read line2 <&6
        read line3 <&6

        echo $line1 
        echo $line2 
        echo $line3 
done

exec 6<&-

Thanks for your answers - I'm am aware of head command but want to use read and file descriptors to display the first three lines

like image 805
frodo Avatar asked Nov 08 '12 16:11

frodo


4 Answers

You could also combine the head and while commands:

head -3 rhyme.txt | 
while read a; do
  echo $a; 
done
like image 110
BeniBela Avatar answered Oct 21 '22 20:10

BeniBela


It reads the first line

while read file <&6 ;

it reads the 2nd, 3rd and 4th line

read line1 <&6
read line2 <&6
read line3 <&6

If you want to read the first three lines, consider

$ head -3 rhyme.txt

instead.

Update:

If you want to use read alone, then leave out the while loop and do just:

exec 6< rhyme.txt

read line1 <&6
read line2 <&6
read line3 <&6

echo $line1 
echo $line2 
echo $line3 

exec 6<&-

or with a loop:

exec 6< rhyme.txt

for f in `seq 3`; do
    read line <&6
    echo $line 
done

exec 6<&-
like image 42
Olaf Dietsche Avatar answered Oct 21 '22 21:10

Olaf Dietsche


There's a read in the while loop, which eats the first line.

You could use a simpler head -3 to do this.

like image 27
unwind Avatar answered Oct 21 '22 19:10

unwind


I got similar task, to obtain sample 10 records and used cat and head for the purpose. Following is the one liner that helped me cat FILE.csv| head -11 Here, I used '11' so as to include header along with the data.

like image 26
Gdek Avatar answered Oct 21 '22 20:10

Gdek