【问题标题】:Read first three lines of a file in bash在 bash 中读取文件的前三行
【发布时间】:2014-10-15 18:02:15
【问题描述】:

我有以下 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<&-

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

【问题讨论】:

  • “head”不是更好的选择吗?像'head -3 rhyme.txt'这样的东西。
  • head -3 有效,但使用head -n 3 更清晰
  • head -3 应该是这里最好的选择。
  • 如果你真的想使用whileread,你也可以使用:while IFS= read -r line; do echo "$line"; done &lt; &lt;(head -n 3 file)

标签: linux bash shell


【解决方案1】:

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

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

【讨论】:

【解决方案2】:

读取第一行

while read file <&6 ;

读取第 2、3、4 行

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

【讨论】:

    【解决方案3】:

    while 循环中有一个 read,它吃掉了第一行。

    您可以使用更简单的head -3 来执行此操作。

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2018-12-11
        • 1970-01-01
        • 1970-01-01
        • 2012-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-27
        • 2022-01-05
        相关资源
        最近更新 更多