Awk is one of the most powerful tools in Unix used for processing the rows and columns in a file.
Awk supports most of the operators, conditional blocks, and loops available in C language.
Basic syntax of AWK
awk 'BEGIN {start_action} {action} END {stop_action}' filename
Example file
Create a file input_file with the following data. (This file can be easily created using the output of ls -l )
-rw-r--r-- 1 center center 0 Dec 8 21:39 p1
-rw-r--r-- 1 center center 17 Dec 8 21:15 t1
-rw-r--r-- 1 center center 26 Dec 8 21:38 t2
-rw-r--r-- 1 center center 25 Dec 8 21:38 t3
-rw-r--r-- 1 center center 43 Dec 8 21:39 t4
-rw-r--r-- 1 center center 48 Dec 8 21:39 t5
From the data, you can check that this file has rows and columns. The rows are separated by a new line character and the columns are separated by a space characters.
Operation 1
awk '{print $1}' input_file
Print the first column in each row.
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
Here $1, $2, $3... represents the first, second, third columns in a row respectively.
To print the 4th and 6th columns in a file use :
awk '{print $4,$6}' input_file
Operation 2
awk '{ if($9 == "t4") print $0;}' input_file
This awk command checks for the string "t4" in the 9th column and if it finds a match then it will print the entire line.
Output
-rw-r--r-- 1 pcenter pcenter 43 Dec 8 21:39 t4
No comments:
Post a Comment
Note: only a member of this blog may post a comment.