I have the following file:
cat testing.txt
==============
line1 1
line2 2 2
line3 3 3
line4
I can understand how the awk 'NF > 0' testing.txt
working. This command is only processing the number of fields with more than 1 field from each record and thus empty lines and tabs are getting removed.
awk 'NF>0' testing.txt
line1 1
line2 2 2
line3 3 3
line4
However I cannot understand how the awk NF testing.txt
is working. It is doing the same as above.
awk NF testing.txt
line1 1
line2 2 2
line3 3 3
line4
I am not specifying any condition in this case. Still it is working fine and removing empty lines and tab from each record.
I can see many references in Web where it is said we can use this command to remove empty lines or tabs from a file. Yet cannot understand the syntax.
NF is a predefined variable whose value is the number of fields in the current record. awk automatically updates the value of NF each time it reads a record. No matter how many fields there are, the last field in a record can be represented by $NF . So, $NF is the same as $7 , which is ' example.
awk '{print $1}' information. txt prints the first column. Then the output of that command (which you saw earlier on) is piped, using the pipe symbol | , to the head command, where its -1 argument selects the first line of the column. If you wanted two lines printed, you'd do: awk '{print $1}' information.txt | head -2.
NR: NR command keeps a current count of the number of input records. Remember that records are usually lines. Awk command performs the pattern/action statements once for each record in a file. NF: NF command keeps a count of the number of fields within the current input record.
In the typical awk program, all input is read either from the standard input (by default the keyboard, but often a pipe from another command) or from files whose names you specify on the awk command line. If you specify input files, awk reads them in order, reading all the data from one before going on to the next.
NF
stands for N
umber of F
ields. So whenever NF
is bigger than 0, that awk
interprets True
. So in fact this is doing:
if NF>0 --> True
if NF==0 --> False
As the default behaviour of awk
is {print $0}
, this means that it does:
if NF>0 ---> True ---> {print $0}
if NF==0 ---> False ---> nothing
So awk NF file
means: print all lines that have at least one field. Which automatically implies: print all no-empty lines.
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