Index

For scratch-pad I need to reverse the order of the records in my log file. The tricky thing is that each record is one or more lines separated by a form feed or page break: “\f” or ^L.

Here’s my 1st version using getline. getline allows us to consume lines without exiting the current rule:

BEGIN { i = 0 }
{
      do {
              sort[i] = sort[i] $0 "\n";
              getline; # Where the magic happens
      } while ($0 != "\f");
      sort[i] = sort[i] $0;
      i += 1;
}
END {
      for (x = i - 1; x > -1; x--) {
             print sort[x];
      }
}

It worked well enough, but there’s something much simpler. In Awk the record separator can be any string, it doesn’t have to be a carriage return. We can change to record separator at runtime using the RS variable. This simplifies things:

BEGIN { RS="\f\n"; i = 0 }
{
      sort[++i] = $0
}
END {
      for (x = i; x > 0; x--) {
             print sort[x] "\f";
      }
}