AWK With Examples 2

Example 5: awk program inside a file(-f option)


awk program can be put inside a file and then used usinng -f option


Below example shows that we create a file nepal.awk with awk program
in it.
Note that when put inside the file, we dont need to write the single quotes.



bos90631:sm017r more nepal.awk
/nepal/ {print $0}



bos90631:sm017r awk -f nepal.awk test1
shushant 7798977047 nepal 200/9000/100



Note: If we dont specify the input file (data file) then awk expects input from standard
input , which normally is keyboard.
We end the input from keyboard by pressing cntl+D.



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

Example 6: awk is case senstive.


Note that awk is case sensitive.
bos90631:sm017r awk '/SUKUL/ ' test1
[No Output]



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




Example 7: Creating awk executable.

We can make the awk script executable and then run it like any other sommand we use .ex: sort etc.

We can do this by putting #! /bin/awk -f at the beginning of script and
make the file executable using chmod.

bos90631:sm017r more nepalexec.awk
#! /bin/awk -f
/nepal/ {print $0}

bos90631:sm017r ls -lrt nepalexec.awk
-rwxrwxrwx   1 sm017r   dba           34 Aug  7 04:43 nepalexec.awk

bos90631:sm017r /export/home/sm017r/nepalexec.awk test1
shushant 7798977047 nepal 200/9000/100

Note: In this example i had to fully qualify the path as current directory is not added as the path of variable PATH. This may not be true on your installation.


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




Example 8: Comments in awk program and continuing on next line.
Comments in awk are like shell comments .ie using #

We can move program text to next line after either of , { ? : || && do else.
Other way is to use the '\' at the end of the line . This technque works
anywhere , even betwen a regular expression.

In below example note that the word 'Jhansi' is broken on two lines.
The program still interprets it as "Jhansi" because of the use or "\".
With this "\" we are actually escaping newline character.

bos90631:sm017r more jhansi.awk
#this code will search for jhansi
/Jh\
ansi/ {print $0}
 

bos90631:sm017r awk -f jhansi.awk test1
bhanu 8097123451 Jhansi 200/1000/500



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

No comments:

Post a Comment