gpt4 book ai didi

Linux head 实用程序只读取一行需要更多输入才能退出

转载 作者:可可西里 更新时间:2023-11-01 11:44:09 26 4
gpt4 key购买 nike

我需要逐行读取连续的数据流(实际上是管道),并且我需要在第一行之后退出。就在第一行之后。听起来很简单,但是,使用“head -n 1”,我注意到我实际上需要在 head 退出之前输入 second 行。

测试用例:

[s@svr1 ~]$ cat | head -n 1    
123 <- I type this first (followed by enter, of course)
123 <- I get this output from head, but the command does no exit
456 <- Then I need to type this for the command to exit and bring me back to the prompt
[s@svr1 ~]$

有人能解释(首先也是最重要的)为什么它会这样吗,也许我怎样才能得到我需要的东西?(我想坚持使用基本的 Linux/Unix 轻量级构建 block 。没有 Perl、Python 等...)

谢谢

最佳答案

因为你正在使用 cat | head -n 1,这是一个 useless use of cat,与 head -n 1 不同。如果您在控制台执行 head -n 1,您将获得所需的行为 — head 读取一行,打印它,然后退出。

如果你做 cat | head -n 1,然后会发生这样的事情:

  1. cat 从其输入中读取“123”。
  2. cat 将“123”写入其输出。
  3. head 从其输入(连接到 cat 的输出)读取“123”。
  4. head 将“123”写入其输出并退出。
  5. cat 从其输入中读取“456”。
  6. cat 尝试将“456”写入其输出。
  7. cat 得到 SIGPIPE 因为其输出另一端的进程已经终止。
  8. cat 退出。

cathead 中写入“123”后立即开始另一次读取,并没有发现head 已死亡直到它尝试向其写入第二行。

关于Linux head 实用程序只读取一行需要更多输入才能退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13536252/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com