awk for-loop and NR

Hey,

I know this is a stupid question, but it doesn't work.
I have a file with 10 lines and I want to pipe the content to awk and then print line 1 til 2 into another file and then line 3-4 ...

So my script looks like that, but doesn't work:

cat grid_ill.pts | awk '{
for (NR=1;NR<3;NR++) {
    print $1, $2, $3, $4, $5, $6 >> "grid_ill_1.pts"}
for (NR=3;NR<5;NR++) {
    print $1, $2, $3, $4, $5, $6 >> "grid_ill_2.pts"}
}'

I guess it doesn't work with NR, but does someone has an idea?
Thanks for any help,
Sam

nawk '{f+=(FNR%2); print >> ("grid_ill_" f ".pts")}'grid_ill.pts

First, in 99% of cases you don't wanna change NR during AWK execution. Second:

awk 'NR<=2{print >> "grid_ill_1.pts";next}{print >> "grid_ill_2.pts"}' grid_ill.pts

yes, thats the problem, but a normal variable in a for-loop cannot adress the NR. Or better to say: I don't know how.

But how can I control from line 2 til line 4 do print with one of these solutions? (In reality the file consists 70 million lines and I have to seperate it into 600000 lines per new file)
Because the nawk-version is writing only writing one line into one file...

Thanks for your help

Perhaps a simple split command will do the trick: Man Page for split (POSIX Section 1) - The UNIX and Linux Forums

Regards,
Alister

juchuuuu. Yes. Works fine and is really cool. I didn't know this command.

Thanks a lot.
Sam

The "nawk-version" should write 2 lines/records per output file.
You can control the number of lines/records per file with 'FNR%2'

I didn't test it, but I don't think you can. It looks to me like that code ony works for FNR%n when n==2, since the result toggles between 1,0,1,0,1,0..., incrementing f as needed. If n==1, FNR%n==0 for all FNR and f always remains 0. When n>2, f will increment on each line read except when FNR%n==0, and the increments will be in steps of f+=1, f+=2, f+=3... f+=(n-1), f+=0, f+=1... creating a discontinous, ever increasing series.

Regards,
Alister

---------- Post updated at 07:50 PM ---------- Previous update was at 07:45 PM ----------

Of course, you can accomodate any n with a slight tweak to the code (initialize f to 1 and only increment f when FNR%n==0). If that's what you meant, disregard the noise.

Have a nice weekend, everyone,
Alister

1 Like

yep, you're right the code (as is) works only for n==2.
Good find - thanks!

nawk '{f+=((FNR%n)==1)?1:0; print >> ("grid_ill_" f ".pts")}' n=2 grid_ill.pts