Linux 在bash中读取文件的前三行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13292756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read first three lines of a file in bash
提问by frodo
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 命令,但想使用读取和文件描述符来显示前三行
回答by unwind
There's a read
in the while
loop, which eats the first line.
有一个read
在 while
循环,吃的第一行。
You could use a simpler head -3
to do this.
您可以使用更简单的方法head -3
来执行此操作。
回答by Olaf Dietsche
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<&-
回答by BeniBela
You could also combine the head and while commands:
您还可以结合使用 head 和 while 命令:
head -3 rhyme.txt |
while read a; do
echo $a;
done
回答by Gdek
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.
我得到了类似的任务,获得样品10条记录和使用cat
,并head
为宗旨。以下是帮助我的一个班轮cat FILE.csv| head -11
在这里,我使用了“11”以便将标题与数据一起包含在内。