2

I'm searching how to put for loop inside "print" - I've managed how to get all information what I need from log file but if I use "for loop" after print then each new information is given in new line. I know that is calling print each time so... how to print all in new line? For example this:

cat /var/log/apache2/domlogs/xxxx/xxxx.com* | awk -F " " '{print $1 " - " $4 " " $5 " "} {for(i=12; i<=NF; i++) print $i}'

Give me that output:

66.249.65.172 - [29/May/2019:02:48:20 +0200]
"Mozilla/5.0
(compatible;
Googlebot/2.1;
+http://www.google.com/bot.html)"

But when I want to pass at end what I found between 12 col and NF:

cat /var/log/apache2/domlogs/xxxx/xxxx.com* | awk -F " " '{print $1 " - " $4 " " $5 " " for(i=12; i<=NF; i++) " " $i}'

Then I get only:

66.249.65.172 - [29/May/2019:02:48:20 +0200]

I'm heading to output like:

66.249.65.172 - [29/May/2019:02:48:20 +0200] "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
2

You need to use printf() over print because the latter by default embeds a newline after the string provided. Modify your code to use printf with format specifiers for each of the strings.

awk '{ printf "%s - %s  %s ", $1, $4, $5 } 
     { for(i=12; i<=NF; i++) printf "%s ", $i; printf "\n" }'
  • Thank you so much - that's did the trick - only I've added extra space here "%s - %s %s " because output had lack of it – TheTanadu May 29 at 5:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.