What can the awk command be used for?

What can the awk command be used for?

The awk command can also be used to count the number of lines, the number of words, and even the number of characters. Let’s start with counting the number of lines with the awk command. The number of lines can be printed by printing out the NR variable in the END section.

How to tell AWK which character to use as separator?

If you want awk to work with text that doesn’t use whitespace to separate fields, you have to tell it which character the text uses as the field separator. For example, the /etc/passwd file uses a colon (:) to separate fields. We’ll use that file and the -F (separator string) option to tell awk to use the colon (:) as the separator.

How does the awk command print the pattern?

Print the lines which matches with the given pattern. In the above example, the awk command prints all the line which matches with the ‘manager’. 3. Splitting a Line Into Fields : For each record i.e line, the awk command splits the record delimited by whitespace character by default and stores it in the $n variables.

How does AWK split a line into fields?

Splitting a Line Into Fields : For each record i.e line, the awk command splits the record delimited by whitespace character by default and stores it in the $n variables. If the line has 4 words, it will be stored in $1, $2, $3 and $4 respectively. Also, $0 represents the whole line.

How does AWK process input in real time?

We saw in the previous example that if no input-source is mentioned then awk simply takes input from the command line. Input under awk is seen as a collection of records and each record is further a collection of fields. We can use this to process input in real-time.

How is the number of words calculated in AWK?

NF is the number of fields in each record. If NF is totalled over all the records, the number of words can be achieved. In the command, c is used to count the number of words. For each line, the total number of fields in that line is added to c. In the END section, printing c would give the total number of words.