Grep 时间命令输出 [英] Grep time command output
问题描述
使用 time ls
,我得到以下输出:
Using time ls
, I have the following output:
$ time ls -l
total 2
-rwx------+ 1 FRIENDS None 97 Jun 23 08:59 location.txt
-rw-r--r--+ 1 FRIENDS None 10 Jun 23 09:06 welcome
real 0m0.040s
user 0m0.000s
sys 0m0.031s
现在,当我尝试仅对 real 值行进行 grep
时,实际结果是:
Now, when I try to grep
only the real value line, the actual result is:
$ time ls -l | grep real
real 0m0.040s
user 0m0.000s
sys 0m0.031s
我的问题是,如何仅获取实际值作为输出?在这种情况下,为 0m0.040s
.
My question is, how to get only the real value as output? In this case, 0m0.040s
.
推荐答案
time
将其输出写入stderr,因此需要使用管道传递stderr而不是stdout.但是也要记住, time
是bash语法的一部分,并且它对整个管道计时.因此,您需要将管道包装在大括号中,或在子 shell 中运行它:
time
writes its output to stderr, so you need to pipe stderr instead of stdout. But it's also important to remember that time
is part of the syntax of bash, and it times an entire pipeline. Consequently, you need to wrap the pipeline in braces, or run it in a subshell:
$ { time ls -l >/dev/null; } 2>&1 | grep real
real 0m0.005s
使用Bash v4.0(在Linux发行版上可能是通用的,但在Mac OS X上仍然不是标准),您可以使用 |&
来同时传送 stdout
和 stderr
:
With Bash v4.0 (probably universal on Linux distributions but still not standard on Mac OS X), you can use |&
to pipe both stdout
and stderr
:
{ time ls -l >/dev/null; } |& grep real
或者,您可以使用 time
实用程序,该实用程序可以控制输出格式.在我的系统上,该实用程序位于/usr/bin/time
:
Alternatively, you can use the time
utility, which allows control of the output format. On my system, that utility is found in /usr/bin/time
:
/usr/bin/time -f%e ls -l >/dev/null
man time
以获得有关 time
实用程序的更多详细信息.
man time
for more details on the time
utility.
这篇关于Grep 时间命令输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!