Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

awk

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?

like image 397
Aaron Digulla Avatar asked Nov 28 '13 09:11

Aaron Digulla


People also ask

What does 1 mean in awk?

1 means to print every line. The awk statement is same as writing: awk -F"=" '{OFS="=";gsub(",",";",$2);print $0;}' Copy link CC BY-SA 3.0.

What is awk '{ print $1 }'?

If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

How do I not print the first row in awk?

The following `awk` command uses the '-F' option and NR and NF to print the book names after skipping the first book. The '-F' option is used to separate the content of the file base on \t. NR is used to skip the first line, and NF is used to print the first column only.

How do I print a specific line in awk?

To print a blank line, use print "" , where "" is the empty string. To print a fixed piece of text, use a string constant, such as "Don't Panic" , as one item. If you forget to use the double-quote characters, your text is taken as an awk expression, and you will probably get an error.


1 Answers

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

like image 61
jkshah Avatar answered Oct 23 '22 15:10

jkshah