![AWK - 新行列印內的“for 循環”](https://rvso.com/image/154449/AWK%20-%20%E6%96%B0%E8%A1%8C%E5%88%97%E5%8D%B0%E5%85%A7%E7%9A%84%E2%80%9Cfor%20%E5%BE%AA%E7%92%B0%E2%80%9D.png)
我正在搜索如何將for 循環放入“print”中- 我已經設法從日誌文件中獲取我需要的所有信息,但如果我在print 後使用“for 循環”,則每個新信息都會在新行中給出。我知道每次都會調用列印,所以...如何在新行中列印所有內容?例如這個:
cat /var/log/apache2/domlogs/xxxx/xxxx.com* | awk -F " " '{print $1 " - " $4 " " $5 " "} {for(i=12; i<=NF; i++) print $i}'
給我輸出:
66.249.65.172 - [29/May/2019:02:48:20 +0200]
"Mozilla/5.0
(compatible;
Googlebot/2.1;
+http://www.google.com/bot.html)"
但當我想最後傳遞我在 12 col 和 NF 之間發現的內容時:
cat /var/log/apache2/domlogs/xxxx/xxxx.com* | awk -F " " '{print $1 " - " $4 " " $5 " " for(i=12; i<=NF; i++) " " $i}'
然後我只得到:
66.249.65.172 - [29/May/2019:02:48:20 +0200]
我要輸出如下:
66.249.65.172 - [29/May/2019:02:48:20 +0200] "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
答案1
您需要使用printf()
over,print
因為後者預設在提供的字串後面嵌入換行符。修改程式碼以printf
與每個字串的格式說明符一起使用。
awk '{ printf "%s - %s %s ", $1, $4, $5 }
{ for(i=12; i<=NF; i++) printf "%s ", $i; printf "\n" }'