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
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<&-
There's a read
in the while
loop, which eats the first line.
You could use a simpler head -3
to do this.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With