【问题标题】:How to print the latest appended content of a text file?如何打印文本文件的最新附加内容?
【发布时间】:2013-12-18 11:49:13
【问题描述】:

我的程序使用文本文件而不是标准输出作为其输出。它不断在文件中添加新行。每次我想附加最新的内容行时,我都可以尾随文件。但现在我希望附加的内容同时显示在我的终端上,就好像我的程序将 stdout 作为其输出一样。

我找到了一个丑陋的解决方案:每五秒打印一次新的附加内容,方法是提前五秒备份文本文件的内容,并用它来区分当前内容,如下所示:

#!/bin/sh
# show the appended text of a file every 5 seconds
echo `pwd`;
while true
do
    cp $1 $1.earlier;
    sleep 5;
    echo `date`;
    diff $1 $1.earlier;
done

【问题讨论】:

  • 使用tail -f怎么样?
  • 天哪!!!我从来不知道 tail 有一个 -f 选项!感谢 Rubens,感谢您协助格式化代码。谢谢汤姆罗恩这么快告诉我正确答案!

标签: bash shell


【解决方案1】:

我想你想要的是:

$ tail -f file

来自man tail

-f, --follow[={name|descriptor}]

output appended data as the file grows; -f, --follow, and --follow=descriptor
are equivalent 

【讨论】:

    【解决方案2】:

    如果您想要的不仅仅是最后几行输出,还有以下内容,您可以调用:

    less +F $file
    

    (或在查看less 中的文件时按Shift-F)。

    在关注文件时,按Ctrl-C 停止关注但保持文件打开,然后按Shift-F 再次关注。

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 1970-01-01
      • 2013-03-11
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 2012-06-12
      相关资源
      最近更新 更多