Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How awk NF filename is working?

Tags:

bash

awk

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.

like image 390
Exploring Avatar asked May 08 '14 14:05

Exploring


People also ask

What does NF do in awk?

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.

What is awk '{ print $1 }'?

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.

What is NR and NF in awk?

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.

How do I read a file in awk?

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.


1 Answers

NF stands for Number of Fields. 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.

like image 172
fedorqui 'SO stop harming' Avatar answered Sep 20 '22 03:09

fedorqui 'SO stop harming'