Bash
將選定欄位寫入單行的 shell 腳本
我有一個日誌文件
trace.log
,它列印時間戳、執行緒名稱和事務方法以及事務 ID,如下所示。2014-01-23 15:50:41,724 [catalina-exec-35] INFO TRANSACTION getConnection REQUEST, ID=1308:: 2014-01-23 15:50:41,725 [catalina-exec-33] INFO TRANSACTION getConnection REQUEST, ID=1304:: 2014-01-23 15:50:41,727 [catalina-exec-10] INFO TRANSACTION getConnection REQUEST, ID=1298:: 2014-01-23 15:50:41,727 [catalina-exec-24] INFO TRANSACTION getConnection REQUEST, ID=1307:: 2014-01-23 15:50:41,727 [catalina-exec-12] INFO TRANSACTION getConnection DONE, ID=1305:: 2014-01-23 15:50:41,733 [catalina-exec-10] INFO TRANSACTION getConnection DONE, ID=1298:: 2014-01-23 15:50:41,734 [catalina-exec-26] INFO TRANSACTION getConnection REQUEST, ID=1313:: 2014-01-23 15:50:41,734 [catalina-exec-26] INFO TRANSACTION getConnection DONE, ID=1313:: 2014-01-23 15:50:41,738 [catalina-exec-39] INFO TRANSACTION getConnection REQUEST, ID=1311:: 2014-01-23 15:50:41,733 [catalina-exec-35] INFO TRANSACTION getConnection DONE, ID=1308:: 2014-01-23 15:50:41,738 [catalina-exec-27] INFO TRANSACTION getConnection REQUEST, ID=1309:: 2014-01-23 15:50:41,737 [catalina-exec-22] INFO TRANSACTION getConnection REQUEST, ID=1310:: 2014-01-23 15:50:41,743 [catalina-exec-30] INFO TRANSACTION getConnection REQUEST, ID=1315:: 2014-01-23 15:50:41,744 [catalina-exec-39] INFO TRANSACTION getConnection DONE, ID=1311:: 2014-01-23 15:50:41,747 [catalina-exec-2] INFO TRANSACTION getConnection REQUEST, ID=1318::
我想在單行中將特定 ID和
grep
的時間戳列印 到文件中。getConnection REQUEST``getConnection DONE
我編寫了一個 shell 腳本,它在多行中列印時間戳,如下所示。這是我的shell腳本
for i in {1..800} do echo "Welcome $i times" echo "ID=$i, getConnection " >> time.log grep ID=$i: trace.log | grep getConnection | cut -d'[' -s -f1 >> time.log echo " " >> time.log done
輸出如下圖
ID=791, getConnection 2014-01-23 15:50:16,703 2014-01-23 15:50:16,706 ID=792, getConnection 2014-01-23 15:50:16,704 2014-01-23 15:50:16,704 ID=793, getConnection 2014-01-23 15:50:16,704 2014-01-23 15:50:16,709 ID=794, getConnection 2014-01-23 15:50:16,708 2014-01-23 15:50:16,712
我怎麼能改變呢?我需要如下所示的輸出:
ID=792, getConnection 2014-01-23 15:50:16,703 2014-01-23 15:50:16,706 ID=792, getConnection 2014-01-23 15:50:16,704 2014-01-23 15:50:16,704 ID=793, getConnection 2014-01-23 15:50:16,704 2014-01-23 15:50:16,709 ID=794, getConnection 2014-01-23 15:50:16,708 2014-01-23 15:50:16,712
不要使用 shell 循環來處理文本,這是不好的做法。
shell 的工作是執行命令(正確的命令)並使它們協作完成一項任務。
在這裡,正確的命令是呼叫一次的實際提取和報告語言解釋器,而不是為文件的每一行執行幾個命令(按順序!)。
perl -lne ' if (/(.*?) \[.*getConnection (.*?), (ID=\d+)/) { if ($2 eq "REQUEST") {$r{$3}=$1} elsif ($2 eq "DONE") {print "$3, getConnection $r{$3} $1" if $r{$3}} }' < your-file
您可以通過將
-n
標誌傳遞給echo
.所以以下應該工作
for i in {1..800} do echo "Welcome $i times" 1>&2 echo -n "ID=$i, getConnection " grep "ID=${i}:" trace.log \ | grep getConnection \ | cut -d'[' -s -f1 \ | while read line do echo -n " ${line}" done echo done >> time.log