AWK With Examples 3

Example 9: Using semicolon

We can put two statements on the same line separated by a semicolon

bos90631:sm017r awk '/77989/{print $0}; /nep/ {print $0}' test1
shushant 7798977047 nepal 200/9000/100
shushant 7798977047 nepal 200/9000/100


Earlier we had seen a similar example where we had written two rules on
separate lines. However thats not compulsory. We can write different statements on same line separated by semicolon.


Example 10: Multiple files as input to awk

We can have multiple files as input to awk program.
The name of the current file is specified by the bult in variable
FILENAME.


cp test1 test2
# we copy our test file as test2


bos90631:sm017r awk '{print FILENAME}' test1 test2
test1
test1
test1
test1
test1
test2
test2
test2
test2
test2


Above awk prints one record for each record in the input file.
Thats is why it prints "test1" 5 times and "test2" 5 times.



Example 11: Using Record Separator.(Built variable RS)

Bult In variable RS indicates the record separator.
Default value is \n

We can change the value to any single character.

This will cause the new character to be assumed as record separator.
We can change the value of RS to another character at any point in the program.
However this is normally done at BEGIN pattern so that it applies to all records.

bos90631:sm017r awk 'BEGIN {RS="/"} {print $0}' 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


We can see that this program assumes / as the record separator.
Thus the program treats "sukul 8149158828 mumbai 100" as 1st record and "900" as second and "200" as 3rd record
RS="" means the records are separated by blank lines.


Example 12: Built in variable FNR and NR

FNR: Current record number in the current file. The value is reset after every file is read
NR:  Number of records overall. This is not reset anytime.


bos90631:sm017r awk '{print NR}' test1 test2
1
2
3
4
5
6
7
8
9
10


Note: FNR does not work on my installation.

No comments:

Post a Comment