Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

Why does "1" in awk print the current line?

In this answer,

awk '$2=="no"{$3="N/A"}1' file

was accepted. Note the 1 at the end of the AWK script. In the comments, the author of the answer said

[1 is] a cryptic way to display the current line.

I'm puzzled. How does that work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In awk,

Since 1 always evaluates to true, it performs default operation {print $0}, hence prints the current line stored in $0

So, awk '$2=="no"{$3="N/A"}1' file is equivalent to and shorthand of

awk '$2=="no"{$3="N/A"} {print $0}' file

Again $0 is default argument to print, so you could also write

awk '$2=="no"{$3="N/A"} {print}' file

In-fact you could also use any non-zero number or any condition which always evaluates to true in place of 1


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...