阅读bash中的第一个三行文件

我有以下shell脚本来读取前三行文件,并将其打印到屏幕 – 它不能正常工作,因为它打印出行2,3,4而不是行1,2,3 – 我在做什么错了?

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

感谢您的答案 – 我知道头命令,但想要使用读取和文件描述符来显示前三行

你也可以结合头和while命令:

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

有一个readwhile循环,吃第一行。

你可以使用更简单的head -3来做到这一点。

它读取第一行

 while read file <&6 ; 

它读取第二,第三和第四行

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

如果你想阅读前三行,请考虑

$ head -3 rhyme.txt

代替。

更新

如果你想单独使用read ,那么就省略while循环,而只是:

 exec 6< rhyme.txt read line1 <&6 read line2 <&6 read line3 <&6 echo $line1 echo $line2 echo $line3 exec 6<&- 

或用循环:

 exec 6< rhyme.txt for f in `seq 3`; do read line <&6 echo $line done exec 6<&- 

我得到了类似的任务,获得样本10条记录,并使用cat目的。 以下是帮助我cat FILE.csv| head -11的一个班轮 cat FILE.csv| head -11在这里,我使用'11'来包含标题和数据。