简体   繁体   中英

Read first three lines of a file in bash

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

You could also combine the head and while commands:

head -3 rhyme.txt | 
while read a; do
  echo $a; 
done

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

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

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<&-

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 cat FILE.csv| head -11 Here, I used '11' so as to include header along with the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM