I have a simple awk one liner that folds the next line onto the current line when a given pattern is matched. Here it is:
awk '/two/ { printf $1; next; } 1' test.txt
with the following input:
one
two
three
four
five
six
one
two
three
four
you get:
one
twothree
four
five
six
one
twothree
four
Note that the "three" is folded up with the "two" which is what I wanted to occur. I found this solution (don't remember where) and thought it odd that the trailing '1' appeared to be the missing piece that resulted in the desired effect. If you take it out, you get:
awk '/two/ { printf $1; next; }' test.txt
twotwo
As the result. So my question is, what does the trailing '1' do, and where is it documented?
Thanks!
AWK works on method of condition and then action. So if any condition is TRUE any action which we mention to happen will be executed then. In case of 1 it means we are making that condition TRUE and in this case we are not mentioning any action to happen, so awk's by default action print will happen.
Hang on and follow with me so you get the flavor of AWK. The characters "\t" Indicates a tab character so the output lines up on even boundries. The "$8" and "$3" have a meaning similar to a shell script. Instead of the eighth and third argument, they mean the eighth and third field of the input line.
The system function allows the user to execute operating system commands and then return to the awk program. The system function executes the command given by the string command. It returns, as its value, the status returned by the command that was executed. Save this answer.
For awk
, 1 mean true, and when an expression is true, awk
print the current line by default.
Examples :
awk '1' /etc/passwd
will print the whole fileawk '0' /etc/passwd
will not print the whole fileIf you're good in arithmetic (or you have imagination or programming skills), there's many tricks you can do with this behaviour.
"The '1' at the end of whole Awk one-liner prints out the modified line (it's syntactic sugar for just "print" (that itself is syntactic sugar for "print $0"))".
-- catonmat
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With