簡體   English   中英

Grep time命令輸出

[英]Grep time command output

使用time ls ,我有以下輸出:

$ 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

現在,當我嘗試僅grep 實際值行時,實際結果是:

$ time ls -l | grep real
real    0m0.040s
user    0m0.000s
sys     0m0.031s

我的問題是,如何只獲得真正的價值作為輸出? 在這種情況下, 0m0.040s

time將其輸出寫入stderr,因此您需要管道stderr而不是stdout。 但同樣重要的是要記住, time是bash語法的一部分,它會占用整個流水線。 因此,您需要將管道包裝在大括號中,或者在子shell中運行它:

 $ { time ls -l >/dev/null; } 2>&1 | grep real
 real   0m0.005s

使用Bash v4.0(在Linux發行版上可能是通用的,但在Mac OS X上仍然不是標准版),您可以使用|&管道stdoutstderr

{ time ls -l >/dev/null; } |& grep real

或者,您可以使用time實用程序,它允許控制輸出格式。 在我的系統上,該實用程序位於/usr/bin/time

/usr/bin/time -f%e ls -l >/dev/null 

man time有關詳細信息, time效用。

(time ls -l)  2>&1 > /dev/null |grep real

這會將stderr(時間發送其輸出的地方)重定向到與stdout相同的流,然后將stdout重定向到dev / null,這樣就不會捕獲ls的輸出,然后將現在輸出的時間輸入到grep的stdin中。

如果您只想指定time builtin的輸出格式,可以修改TIMEFORMAT環境變量的值,而不是使用grep過濾它。

在你的情況下,

TIMEFORMAT=%R
time ls -l

會給你“真正的”時間。

以下是 Bash手冊中相關信息的鏈接 (在“TIMEFORMAT”下)。

關於解析time輸出, 是一個類似的問題。

請注意.. bash有一個內置的“時間”命令。 以下是一些差異..

# GNU time command (can also use $TIMEFORMAT variable instead of -f)
bash> /usr/bin/time -f%e ls >/dev/null
0.00


# BASH built-in time command (can also use $TIME variable instead of -f)
bash> time -f%e ls >/dev/null
-f%e: command not found

real    0m0.005s
user    0m0.004s
sys     0m0.000s

我想,它可以變得更容易一些:

time ls &> /dev/null | grep real

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM