Awk notes
I love awk and use it a lot. Yesterday, I used it for something with multiline records. Awk on single lines is quick and easy to use, but I always have to look up what to do with multiline records. And I still don’t exactly understand everything about multiline records, but here’s what worked for me.
Say I had this file:
George Washington 1789 - 1797 John Adams 1797 - 1801 Thomas Jefferson 1801 - 1809 James Madison 1809 - 1817
I needed to reverse the order of the records like this:
James Madison 1809 - 1817 Thomas Jefferson 1801 - 1809 John Adams 1797 - 1801 George Washington 1789 - 1797
The first thing I needed to do was to create a file with my awk commands because they’re going to be a little long to type at the prompt.
BEGIN { RS = "" ; FS = "\n" } { print $1 }
RS = Record separator
FS = Field separator
And then I’m just going to print out just the name (which is field #1).
$ awk -f y samp.txt George Washington John Adams Thomas Jefferson James Madison
Ok, now I want to reverse the order and just print the entire record.
$ cat x # The BEGIN section is run once at the start. Here we just set up some separators BEGIN { RS = "" ; FS = "\n" } # The middle section is what runs over the file. Here we're just adding each record to an array { a[i++]=$0 } # The END section runs once. Here we print out the array starting at the end and working back to the beginning END {for (j=i-1; j>=0;) print a[j--] "\n"} $ awk -f x samp.txt James Madison 1809 - 1817 Thomas Jefferson 1801 - 1809 John Adams 1797 - 1801 George Washington 1789 - 1797