Awk processes multiple rows of records and awk processes multiple rows
The records of input files used in all our examples are composed of a single row. In this section, we will demonstrate how to read a record, and each field in the record is composed of a single row.
We have learned an example of a file that processes the name and address. Let's assume that the same data is saved in a block format file. Instead of placing all the information in one row, place the person's name in one row, place the company name in the next row, and so on. Below is a record sample:
John Robinson
Koren Inc.
978 Commonwealth Ave.
Boston
MA 01760
696-0987
This record has six fields, which are separated by empty rows. To process this record that contains multiple rows of data, we can define the field separator as a line break, the line break is represented by "\ n", and the record separator is set as a null string, it represents a blank line.
BEGIN {FS = "\ n"; RS = ""}
We can use the following script to print the first and last fields:
$ Cat block. awk
# Block. awk-print the first and last Fields
#$1 = name; $ NF = phone number
BEGIN {FS = "\ n"; RS = ""}
{Print $1, $ NF}
The running result of the example is as follows:
$ Awk-f block. awk phones. block
John Robinson 696-0987
Phyllis Chapman 879-0900
Jeffrey Willis 914-636-0000
Alice Gold (707) 724-0000
Bill Gold 1-707-724-0000
The two fields are output in the same line because the default output field separator (OFS) is still a space. If you want to output these fields on different rows, you can change the OFS value to a line break. In this way, you may want to use spaces to separate records. Therefore, you must set the ORS of the output record as two line breaks.
References: http://www.linuxawk.com/communication/497.html