NRFNR in awk

Source: Internet
Author: User

NRFNR in awk

In shell programming, awk is a powerful tool. You can think of it as a part of shell or a separate language with powerful functions. Let's talk about NR and FNR today.

Prepare two files first:

1. txt with the following content:

User password

Wolf 123456

Zys 123

2. txt content:

Id user

0001 wolf

0002 xiaozhai

In fact, when processing a single file, NR is the same as FNR, indicating the row number currently read, for example, run awk '{print NR}' 1.txt and run awk '{print FNR}' 1.txt, and the results are the same.

1

2

3

However, when processing two files, awk first reads the first file. At this time, NR is equal to FNR. However, when reading the second file, FNR starts counting again, while NR continues to grow, this is not the same,

Run awk '{print NR "\ t" FNR}' 1.txt 2. The txt result is as follows:

1 1

2 2

3 3

4 1

5 2

6 3

Password in begin, and the user name and password are printed. awk 'nr = FNR {a [$1] = $2; next} {if (a [$2]) {print $2 "\ t" a [$2] ;}' 1.txt 2.txt. Be sure to use single quotation marks and the result is:

User passwd

Wolf 123456

Explain this command: In the "users" column of "tables", if there is a record corresponding to the user of the current row in array a, print the user (that is, $2) and passwd (that is, a [$2]).

Awk functions are really powerful.

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.