awk array next issue

Hi,

Here's an example of what I my issue, a file list.txt, which looks like:

a
b
c
d
e

I have been trying to use the following code to simply print the list using awk and next:

awk 'FNR==NR{a[$1]=$1;next}{print a[$1]}' list.txt

this give no output, even though I would expect it to type out the list. Removing the next command works fine:

awk 'FNR==NR{a[$1]=$1}{print a[$1]}' list.txt

What am I missing? Why doesn't the first code work?

next means it jumps to the end of the script, skipping the following program code.
next is useful with two input files.
The first one (where FNR==NR is true) reads into the array, and the following code is skipped.
During the second file (where FNR!=NR i.e. skips the following {block} ) it runs the code following the skipped {block} .

To keep the forums high quality for all users, please take the time to format your posts correctly.

First of all, use Code Tags when you post any code or data samples so others can easily read your code. You can easily do this by highlighting your code and then clicking on the # in the editing menu. (You can also type code tags

```text
 and 
```

by hand.)

Second, avoid adding color or different fonts and font size to your posts. Selective use of color to highlight a single word or phrase can be useful at times, but using color, in general, makes the forums harder to read, especially bright colors like red.

Third, be careful when you cut-and-paste, edit any odd characters and make sure all links are working property.

Thank You.

The UNIX and Linux Forums

To clarify what MadeInGermany wrote:
With that particular awk construct (your first example), you need to specify two input files, not one. With one file, the print part never gets executed.

Also, there seems to be a typo, NFS should be FNR .

1 Like

Thanks for the hint, I have corrected my post.

Hello hexy,

Adding to Made in Germany's point here too. next is useful for another thing too. So let's say we have many conditions in our program(which are NOT dependent on each other), we could use next and could tell awk NOT to go further checks and could save some cycles there.

Thanks,
R. Singh