【问题标题】:bash while loop drops last line of text file [duplicate]bash while循环删除文本文件的最后一行[重复]
【发布时间】:2026-02-20 10:30:01
【问题描述】:

当我 cat 这个文件时,我得到 6 行(它是一个 diff 文件)

bash-3.00$ cat /tmp/voo
18633a18634
> sashabSTP
18634a18636
> sashatSTP
21545a21548
> yheebash-3.00$

但是,当我逐行阅读时,我只得到 5 行。

bash-3.00$ while read line ; do echo $line ; done < /tmp/voo
18633a18634
> sashaSTP
18634a18636  
> sashatSTP
21545a21548

或者这个

bash-3.00$ cat /tmp/voo | while read line ; do  echo $line ; done
18633a18634
> sashabSTP
18634a18636
> sashatSTP
21545a21548
bash-3.00$

我错过了 while 循环中的最后一行“yhee”。

【问题讨论】:

    标签: bash loops while-loop


    【解决方案1】:

    注意:

    21545a21548
    > yheebash-3.00$
          ^---- no line break
    

    您的文件不会以换行符终止。

    【讨论】:

    • 你明白了 - 输出是 cron 驱动的 - 我想我会在最后一行添加一个 echo 命令。
    • 您还可以使用while read line || [ -n "$line" ]; do 使while 循环运行到未终止的最后一行(请参阅this previous answer)。
    【解决方案2】:

    如果您想知道为什么?this might satisfy your curiosity

    如果您使用的文件结尾可能会或可能不会以新行结尾,您可以这样做:

    while IFS= read -r line || [ -n "$line" ]; do
      echo "$line"
    done <file
    

    或者这个:

    while IFS= read -r line; do
      echo "$line"
    done < <(grep "" file)
    

    阅读更多:

    1. https://*.com/a/31397497/3744681
    2. https://*.com/a/31398490/3744681

    【讨论】: