使用head -n1获取osx上grep的第一个匹配项

时间:2017-09-12 10:35:36

标签: bash macos grep head

我正在尝试使用head -n1来获得第一个grep匹配(建议几个地方)

我希望这可行

$ printf "x=0;\nwhile True:\n x+=1\n print x" | python | grep -w 333 | head -n1

(把一些永远存在于grep命令中的东西,它将选择一行,然后从该输出中取出第一行)

然而,没有输出,它永远不会停止。

这可以按预期工作:(取第一行无限输出,不带grep)

$ printf "x=0;\nwhile True:\n x+=1\n print x" | python | head -n1
1
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
IOError: [Errno 32] Broken pipe

这样可行:( grep输出并获得单个匹配)

$ printf "x=0;\nwhile True:\n x+=1\n print x" | python | grep -w 333
333

(并且永不退出)

但是,这种组合并不能满足我的期望:

$ printf "x=0;\nwhile True:\n x+=1\n print x" | python | grep -w 333 | head -n1

(从不打印任何东西,永不退出)

2 个答案:

答案 0 :(得分:3)

您需要在--line-buffered中使用grep选项:

printf "x=0;\nwhile True:\n x+=1\n print x" | python | grep --line-buffered -w 333 | head -n 1
333

根据man grep

--line-buffered
     Force output to be line buffered.  By default, output is line buffered when standard
     output is a terminal and block buffered otherwise.

但请注意,由于您在python代码中运行无限循环,因此命令不会退出。

如果您希望在首次打印后立即退出管道,请使用awk

printf "x=0;\nwhile True:\n x+=1\n print x" | python |& awk '$1=="333"/{print; exit}'
333

答案 1 :(得分:1)

BSD grep on macOS > 10.9支持-m选项:

-m num, --max-count=num
     Stop reading the file after num matches.

因此,您可以跳过头部并使用-m1

$ printf "x=0;\nwhile True:\n x+=1\n print x" | python | grep -w 333 -m1
333
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>