Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

awk Command

Question: What is awk?


The awk command is one of the more unusual UNIX commands. It combines pattern matching, comparison making, line decomposition, numerical operations, and C-like programming features into one program. A basic awk command line looks like this -

                        awk awk-command filename

In general, each awk command has a line-specifier (a pattern) part followed by an instruction (an action) awk allows us to identify particular fields within a line. By default, a field is a sequence of characters containing no blanks and separated by blanks from other fields. For example, each word on this line is a separate field. Its actions provide for numerical operations, for creating variables, and for providing programming flow control statements.

A simple example of an awk command line is as -
        awk'/poultry/{print $1,$3,$6}' supplies

In this case, the pattern part is/poultry/. This matches those lines containing the string poultry. The action part is enclosed in braces: it requests that the first, third and sixth fields of matching line be printed. The $1 stands for the first field, the $3 stands for the third field, and so on.

If there is no pattern portion, the action is applied to every line of input. Thus, the following prints the first and second fields of the file table 2 in reversed order -

                      awk '{print $2, $1}' table 2

If there is no action portion, the default action is to print the entire line. Thus, thefollowing prints all lines of the file nat.enq containing the string scandal -

                   awk '/scandal/' nat.enq

More than one command can be included by starting a new line for each command -

                   $ awk'/candal/{print $0}/rumor/{print $0}'rag

The $0 stands for the entire line.

If we have many commands, it is more convenient to place them in a file and have awk get its commands from the file. This is acheved by using -f option:
                  awk-f cawk rag

This command tells awk to apply the command in the cawk file to the input from the rag file.

awk statements are usually applied to all lines selected by the address, and if there are no address, then they are applied to every line of input.

Features of awk Command are as follows:

1.)   Ability to view a text file as made up of records and fields on a textual database.

2.)   Use of arithmetic and string operators

3.)   Use of variables to manipulate the database

4.)   Use of common programming constructs such as loops and conditions

5.)   Ability to generate formatted reports

6.)   Define functions

7.)   Handling command line arguments

8.)   Handling multiple input stream.

This post first appeared on BCA MCA NOTES, please read the originial post: here

Share the post

awk Command


Subscribe to Bca Mca Notes

Get updates delivered right to your inbox!

Thank you for your subscription