A A A
logo2




How to run awk programs?



Awk scripts you can run In two ways:

  • First:

Write in command line script and name of data file

owi@laptop:~$ awk 'script' data

  • Second:

The scripts is written in another file.

owi@laptop:~$ awk -f skrypt data

Syntax



pattern {action }

The part pattern shows which lines we will change. The part action tell us what we will do with do. If there won’t be part pattern , the action will be done for all lines. If there is no action the lines will be only print.


Example 1



owi@laptop:~$ awk '{printf $0}' data

There is no pattern so the scripts will be done for All lines. There will be print all lines from data file.



Example 2


owi@laptop:~$ awk '$2>10' data

There is no action so it will be print only that lines where in second column is number bigger then 10.



Example 3


owi@laptop:~$ awk '$2>10 {printf $1}' data

This time is action and pattern. Pattern tell as that we will take only lines where in second column is number bigger then 10. The action will print from this lines only first and second column.



Example 4


owi@laptop:~$ awk '$1==”ala” {printf $2}' data

For lines where In first column is Word „Ala” will be print second column.


BEGIN i END
The scripts will do some action for lines which match to pattern. If you want to some action to be done at beginning use BEGINN.



Przykład 5

You can use BEGINN to add head-line
owi@laptop:~$ awk 'BEGIN { print "login" ,"number"} $4>10 {print $1,$2}' data

At first tere is printed „login liczba” and then tere is done command $4>10 {print $1,$2}.


Variable
There is few special variables for example NR-number of records, FS-file separator, NF-number of files.



Example 6

In file /etc/passwd files are separatek with symbol „:”. If you want print for example second column you must use BEGINN and variable FS=”:”.
owi@laptop:~$ awk 'BEGIN { FS=":" } $3>100 {print $1}' /etc/passwd

END works like BEGINN but it makes action at the end of the scripts.


Przykład 7

Variable NR tell us in witch line is now. If you will use it at the end of a script there will be print the number of all records.
owi@laptop:~$ awk '$2>1 {print $1,$2} END{print "How much lines:" NR-1}' data




Conditions



If
If condition looks like in C programming language.

if (condition) { ... } else { ... }




Example 8

owi@laptop:~$ awk '{print $0} END { if(NR>10) print "A lot of lines"; else print "Few lines"}' data

The scripts will print at the end of scripts „a lot of lines when tere will be more then 10 lines Or „little lines” when there is less then 10 lines.


Autor: Aleksandra Przybyło
aleksandraprzybylo@gmail.com