你能在用 tee 寫的每一行前面加上目前日期和時間嗎?

你能在用 tee 寫的每一行前面加上目前日期和時間嗎?

我使用“tee”命令來將長 bash 命令的結果捕獲到檔案中。

我用 tee 發出的文件可以以某種方式在每行前面加上寫入該行時的時間戳嗎?我正在尋找一種解決方案,其中每行都有不同的日期時間值...而不是每行上的前綴相同的值。

我想要這個的原因是,當我閱讀文件以了解慢速區域在哪裡時,了解每行何時發出將非常有用。

答案1

如果 tee 不能做某事,請將其通過管道傳輸到可以做某事的程序。更多實用程式有一個名為的工具,ts其用途正是如此:

$ 迴聲測試 | ts
2月2日 13:17:27 測試

如果你想加時間戳一切,用法應該很明顯:

myapp | ts | tee app.log

其他組合也是可能的;例如,僅對螢幕輸出或日誌檔案新增時間戳:

myapp | tee app.log | ts
myapp | tee >(ts > app.log)
myapp | tee /dev/tty | ts > app.log
myapp | pee "ts > app.log" "cat"
myapp | pee "cat > app.log" "ts"

(是的,最後一個也來自 moreutils。)

答案2

替代方案ts

echo "foo" | stdbuf -o0 sed 's/%/%%/g' | xargs -d '\n' -I {} date '+%F %T {}' | tee -a "/tmp/foo.log"

輸出:

# cat "/tmp/foo.log"
2022-02-24 09:43:00 foo

將 stdout 和 stderr 記錄到檔案的範例(/dev/null也刪除以寫入終端):

exec &> >(stdbuf -o0 sed 's/%/%%/g' | xargs -d '\n' -I {} date '+%F %T {}' | tee -a "/tmp/std.log" >/dev/null )

另一個選擇是使用awk

echo "foo" | xargs -d'\n' -I{} echo '{}' | awk '{ print strftime("%F %T"), $0; fflush(); }' | tee -a "/tmp/foo.log"

相關內容