Usage of Int with NR in awk

Hello Everyone,

I am new to awk and trying my hand with the diff codes and came across the below code today. It would be great if any of the Guru's help me to understand.

awk '{filename = "sample_file" int((NR-1)/34) ".DAT"; print >> filename}' sample_file.DAT

34 is the no of lines each file should be splitted into. The above command is writted to splie the file sample_file.DAT to have 34 lines each. Can somebody tell me how these int ((NR-1)/34) works. I blieve NR is nothing but the no of lines in the input file.

Try yourself. Run:

awk 'BEGIN {for (i=1; i<=69; i++) print i, "filename" int((i-1)/34)".DAT"}'
1 Like

Hi RudiC,
Got it.so NR is nothing but the no of lines read by the awk and the for loop printed me 1 till 69.

NR is you the total number of records being processed or line number

Yeah.

awk '{filename = "sample_file" int((NR-1)/34) ".DAT"; print >> filename}' sample_file.DAT

In that code, so this is how I understand,
first iteration , it reads till 34th line 34-1/34 and it will put 0 and the file name will be sample_file0.DAT and then it will print till that line into that file sample_file0.DAT... the second iteration it will be 68-1/34 and it will round the integer to 1 and the file name will be sample_file1.DAT and so on.. Is it correct.?

More or less correct, but int() doesn't round, it truncates, throwing away everything after the decimal point whether it be it #.0000000000034 or #.9999999999999999977.

NR is the number of records. awk uses \n to separate records by default, but can use anything you tell it to. It can be useful to set it to < to parse XML files for example.

1 Like

Yes Corona688. You are correct int truncate. This is the reason I get 0 ,1 .. so on.. But I have one more doubt, how does awk know that it has to print the first 34 lines to first set of file and so on..

It doesn't, it just does what it's told -- print each line into filename.

And since filename is calculated from the line number each line, the file name changes depending on the equation we just explained.

1 Like