A simple awk command

Hi there,

given the file

FIELD1    FIELD2  FIELD3   FIELD4 FIELD5 FIELD6    FIELD7  FIELD8 FIELD9  FIELD10 FIELD11

Why does not

awk '$6 == "FIELD6" {$6=="GREEN"}1' file

do the work and replace"FIELD6" by "GREEN"?

And second question, what is the purpose of the "1" at the end of the string before "file"?

Cheers

Try:

$6="GREEN"

--

Everything in awk has the form condition{action} . If the condition evaluates to 1 then the action is performed. If the condition is omitted then the default condition is 1, so the action is always performed. If the action is omitted then the default action is performed, which is {print $0} . In this case the condition is 1 (true) and the action is omitted, therefore {print $0} is performed, which is "print the entire record".

what a silly mistake. Thank you!
PS,
any hint what is the purpose of that "1"?

As Scrutinizer described in his last post, it causes your output to be printed. Without it, you change data on some lines in an internal buffer, but never print the results.

Hello la2015,

Let me try to make it simple and explain you. awk works on a theme which is <:condition:><:action/operations:> so lets say if you have given one condition as follows:

awk '($1>2){print $0}'  Input_file

So in above example you are checking condition if $1 is greater than 2 then if condition is TRUE then you are asking it to perform action {print $0} , which will print the $0(means complete line) whose $1 is grater than value 2. Now if we are giving like as follows.

 awk '($1>2)' Input_file
 

So in above example whenever condition is going to be TRUE then as there is NO action given by us to perform so awk will perform the default action which is printing the line. Similarly by giving 1 in code we are making condition TRUE and not giving any further actions so when condition is TRUE and no action given so awk will do default action which is print. Hope this helps you, enjoy learning :b:

EDIT: Like an example as follows.

 awk '($1>2){next} 1' Input_file
 

So in above example you are giving condition like if $1 is grater than 2 then perform action which is next , means don't do any further action but if condition is FALSE then it will not perform any action and will go to 1 and as 1 will make condition TRUE with no action further given so it will print the line, so basically whichever line's $1 is grater than 2 we are skipping them here.

Thanks,
R. Singh

thank you everyone for such detailed explanations!