简体   繁体   English

在bash中读取文件的前三行

[英]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 ? 我有以下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<&-

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 感谢您的回答 - 我知道head命令但是想要使用读取和文件描述符来显示前三行

You could also combine the head and while commands: 您还可以组合head和while命令:

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

There's a read in the while loop, which eats the first line. while循环中有一个read ,它占用了第一行。

You could use a simpler head -3 to do this. 您可以使用更简单的head -3来执行此操作。

It reads the first line 它读取第一行

while read file <&6 ;

it reads the 2nd, 3rd and 4th line 它读取第2行,第3行和第4行

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

If you want to read the first three lines, consider 如果你想阅读前三行,请考虑

$ head -3 rhyme.txt $ head -3 rhyme.txt

instead. 代替。

Update : 更新

If you want to use read alone, then leave out the while loop and do just: 如果你想单独使用read ,那么请省略while循环并执行以下操作:

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. 我得到了类似的任务,获取样本10条记录并使用cathead为目的。 Following is the one liner that helped me cat FILE.csv| head -11 以下是帮助我cat FILE.csv| head -11的一个班轮 cat FILE.csv| head -11 Here, I used '11' so as to include header along with the data. cat FILE.csv| head -11在这里,我使用'11'以便包含标题和数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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