Process a file for line count using for loop in awk

Hi,

I have a file with contents

So what I have to do is

In short, break the file after every 6 lines and then truncate new line to tab for these 6 lines.
I am not able to execute the for loop in awk properly.
The idea is something like this:
less file| awk '{for .... {if ((nr>=1) && (nr<=6)) print $0}}'| tr "\n" "\t"

Can someone help me on this

Hi Rossi,

Use below code:

  
 awk '{A[(NR-1)%6]=A[(NR-1)%6]$0" ";next}END{for(i in A)print A}' fileName
 

Hi Shilpi,

the output from your code is

I am looking for something else.

But thanks, it might be useful for other problems.

Try this:

awk 'NR % 6 {printf $0 FS; next}1'  file
1 Like
$ perl -pe 's/\n/ / unless ($. % 6) == 0' file
Name = abc HPScore = 6.00 HMScore = 7.99 HSScore = 7.73 Pre avg = 2.90 Pre bind ene =1.09
Name = djhf HPScore = 16.00 HMScore = 17.99 HSScore = 17.73 Pre avg = 21.90 Pre bind ene =111.09
Name = sgs HPScore = 12.00 HMScore = 43.99 HSScore = 72.73 Pre avg = 25.90 Pre bind ene =14.09
Name = lksf HPScore = 61.00 HMScore = 34.99 HSScore = 1.73 Pre avg = 34.90 Pre bind ene =12.0

or the reverse

perl -pe 's/\n/ / if ($. % 6)' file
1 Like

Thanks Fraklin and Aia,

It works, I will try to understand the logic of doing these tasks in the future.

awk 'NR % 6 {printf $0 FS; next}1'  file

NR % 6 : evaluates if the line number is a multiple of 6. if evaluates as non-zero line must be truncated. 0 skip this action and go to the final action (final 1)
printf $0 FS; : display the current record + a Field Separator (in this case default space)
next : continue to the next record and do not evaluate anything else
1 : it can be any non-zero, and makes awk to use the default action of print $0, if you get to this point

perl -pe 's/\n/ / unless ($. % 6) == 0' file

-pe : print all lines
s/\n/ / unless ($. % 6) == 0 : substitute the end of line for space unless that the line number is a multiple of 6

awk '{printf "%s%s",$0,(NR % 6) ? OFS : ORS}' file

The previous printf $0 FS should be printf "%s ",$0 so it can print % signs.