0

I have a piece of code, I am trying to break down and decipher. I need someone that can walk me through what is happening in each step:

FNR==NR {
  if (split($1,a, "_") ==3)
  f1[$1]
next
}
NF{
if (split($1, a, "_") ==3 && $1 in f1)
  p=1
  rec=(!rec)?$0:rec ORS $0
next
}
p{
  print rec ORS
  p=0; rec=""
}
0

NR is the total number of records processed (inclusive of the one being processed currently); FNR is the number of records processed in the current file. This will only happen for the first file.

FNR==NR {
  if (split($1,a, "_") ==3)
  f1[$1]
next
}

Similarly, NF is the number of fields in the current record. If it is a blank line, this will be zero, which is "falsy" (as opposed to "truthy"), and so this block will only execute for non-blank lines. Make a note of the code in this block where the value of p is set; that will be important later. ORS is the Output Record Separator; this is what separates each record as it is written out. By default is is a newline. Here is is conditionally used as the value for the rec variable.

NF{
if (split($1, a, "_") ==3 && $1 in f1)
  p=1
  rec=(!rec)?$0:rec ORS $0
next
}

This last block will run only if the value of p is "truthy".

p{
  print rec ORS
  p=0; rec=""
}
|improve this answer|||||
  • Thanks, what does this actually mean: (split($1,a, "") ==3) and if (split($1, a, "") ==3 && $1 in f1) – user236443 Jun 28 '17 at 18:35
  • Lots of reading here on those. split(string, array [, fieldsep [, seps ] ]) will divide string into pieces separated by fieldsep and store the pieces in array and the separator strings in the seps array. – DopeGhoti Jun 28 '17 at 18:42

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.