Backspace Mild
Backspace Mild

Reputation: 1

Why does NR==FNR; {} behave differently when used as NR==FNR{ }?

Hoping someone can help explain the following awk output.
awk --version: GNU Awk 5.0.1, API: 2.0 (GNU MPFR 4.0.2, GNU MP 6.2.0)
OS: Linux sub system on Windows; Linux Windows11x64 5.10.102.1-microsoft-standard-WSL2
user experience: n00b

Important: In the two code snippets below, the only difference is the semi colon ( ; ) after NR==FNR in sample # 2.

sample # 1 'awk 'NR==FNR { print $0 }' lines_to_show.txt all_lines.txt
output # 1
2
3
4
5
7

sample # 2 'awk 'NR==FNR; { print $0 }' lines_to_show.txt all_lines.txt
output # 2
2 # why is value in file 'lines_to_show.txt appearing twice?
2
3
3
4
4
5
5
7
7
line -01
line -02
line -03
line -04
line -05
line -06
line -07
line -08
line -09
line -10

Generate the text input files
lines_to_show.txt: echo -e "2\n3\n4\n5\n7" > lines_to_show.txt
all_lines.txt: echo -e "line\t-01\nline\t-02\nline\t-03\nline\t-04\nline\t-05\nline\t-06\nline\t-07\nline\t-08\nline\t-09\nline\t-10" > all_lines.txt

Request/Questions:

What have I tried so far?

  1. going though https://www.linkedin.com/learning/awk-essential-training/using-awk-command-line-flags?autoSkip=true&autoplay=true&resume=false&u=61697657
  2. modifying the code to see the difference and use that to 'understand' what is going on.
  3. trying to work through the flow using pen and paper
  4. going through https://www.baeldung.com/linux/awk-multiple-input-files --> https://www.baeldung.com/linux/awk-multiple-input-files

Upvotes: 0

Views: 386

Answers (2)

dan
dan

Reputation: 5241

man awk is the best reference:

An awk program is composed of pairs of the form:

pattern { action }

Either the pattern or the action (including the
enclosing brace characters) can be omitted.

A missing pattern shall match any record of input,
and a missing action shall be equivalent to:

{ print }

; terminates a pattern-action block. So you have two pattern/action blocks, both whose action is to print the line.

Upvotes: 0

Daweo
Daweo

Reputation: 36590

awk 'NR==FNR { print $0 }' lines_to_show.txt all_lines.txt

Here you have one pattern-action pair, that is if (total) number of row equals file number of row then print whole line.

awk 'NR==FNR; { print $0 }' lines_to_show.txt all_lines.txt

Here you have two pattern-action pairs, as ; follows condition it is assumed that you want default action which is {print $0}, in other words that is equivalent to

awk 'NR==FNR{print $0}{ print $0}' lines_to_show.txt all_lines.txt

first print $0 is used solely when processing 1st file, 2nd print $0 is used indiscriminately (no condition given), so for lines_to_show.txt both prints are used, for all_lines.txt solely 2nd print.

Upvotes: 2

Related Questions