Read the first three lines of a file in bash

I have the following shell script to read in the first three lines of the file and print them to the screen - it does not work correctly because it prints 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 know about the head command, but you want to use read and file descriptors to display the first three lines

+4
source share
4 answers

You can also combine the head and commands:

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

There is read in a while that eats the first line.

For this you can use a simpler head -3 .

+6
source

He reads the first line

 while read file <&6 ; 

he reads the 2nd, 3rd and 4th lines

 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 only read , leave a while and execute:

 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<&- 
+5
source

I had a similar task to get samples of 10 records and use cat and head for this purpose. Below is one liner that helped me cat FILE.csv| head -11 cat FILE.csv| head -11 Here I used "11" to include a header along with the data.

+1
source

Source: https://habr.com/ru/post/1444860/


All Articles