Awk processes multiple rows of records and awk processes multiple rows

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.