获取shell命令输出的第一行 [英] Get first line of a shell command's output
问题描述
在尝试读取vim
的版本号时,我得到了很多其他需要忽略的行.我尝试阅读head
的手册,并尝试了以下命令:
While trying to read the version number of vim
, I get a lot additional lines which I need to ignore. I tried to read the manual of head
and tried the following command:
vim --version | head -n 1
我想知道这是否正确吗?
I want to know if this is the correct approach?
推荐答案
是的,这是从命令获取第一行输出的一种方法.
Yes, that is one way to get the first line of output from a command.
如果命令以相同的方式输出任何您想要捕获的标准错误,则需要将命令的标准错误重定向到标准输出流:
If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:
utility 2>&1 | head -n 1
还有许多捕获第一行的方法,包括sed 1q
(在第一行之后退出),sed -n 1p
(仅打印第一行,但读取所有内容),awk 'FNR == 1'
(仅打印第一行,但是再读一遍)等.
There are many other ways to capture the first line too, including sed 1q
(quit after first line), sed -n 1p
(only print first line, but read everything), awk 'FNR == 1'
(only print first line, but again, read everything) etc.
这篇关于获取shell命令输出的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!