AWK With Examples 1


How awk works (in brief):

Awk works as " search for pattern in the records of the file and if found perform actions on the line"

Awk program consists of Rules- A Rule consists of two things- Pattern and Action.

Pattern to search for and action to perform when pattern is found.


###########################################

Example 1:

Search for the pattern 81491 and print the records having this text.

bos90631:sm017r awk ' /81491/ {print $0} ' test1
sukul 8149158828 mumbai 100/900/200
uma 8149122222 chennai 100/800/300

Note that entire program is enclosed inside single quotes.

Pattern / / is used for regular expresions.

print $0 and print both are the same. Both print the entire record.

Here print is the action and the action is enclosed within {}


###########################################

Example 2:

Pattern is what helps us select the rows and action indicates
what to do with the rows selected. Actions are always written inside {}.


Either the pattern or action can be omitted but not both.

If pattern is omitted then action is performed on every line.

If action is omitted default action is to print the entire record.

# skipping pattern
bos90631:sm017r awk ' {print }' test1
sukul 8149158828 mumbai 100/900/200
uma 8149122222 chennai 100/800/300
bhanu 8097123451 Jhansi 200/1000/500
shushant 7798977047 nepal 200/9000/100
himanshu 9090909090 bokharo 100/800/300


# skipping action
bos90631:sm017r awk '/81491/ ' test1
sukul 8149158828 mumbai 100/900/200
uma 8149122222 chennai 100/800/300


###########################################

Example 3: Empty action field

Empty action field is different than no action.
Not writing {} and not writing anything in {} are two different things.
Not writing anything within {} will print nothing.
There will be no output.


bos90631:sm017r awk '/81491588/ {} ' test1
[no output]



###########################################

Example 4: Multiple rules in single awk program.

We can have multiple rules in a awk program.
Multiple rules can be coded one after another.


If a record satisfies multiple rules then multiple actions will be carried
out on that record.


Example:
awk '/sh/ {print $0}
 /nepal/ {print $0}' test1


In above example /sh/ is the 1st pattern and /nepal/ is the 2ns pattern.

Below shows that one record matches both the patterns "sh" and "nepal"
and hence is printed twice(2 actions)

bos90631:sm017r awk '/sh/ {print $0}
        /nepal/ {print $0}' test1>     
shushant 7798977047 nepal 200/9000/100
shushant 7798977047 nepal 200/9000/100
himanshu 9090909090 bokharo 100/800/300


###########################################

2 comments: