awk command in Linux

awk command in Linux

More than a command Awk is a scripting language that is used for manipulating data which can be used to do various operations on file reports.

More than a command we can think of Awk as a supporting tool or the utility which enables a programmer to write tiny but effective programs in the form of statements that define text patterns that are to be searched for in each line of a document and the action that is to be taken when a match is found within a line.

WHERE AWK CAN BE USEFUL?

(a) When we want to scan file line by line.

(b)When we want to split each input line in the field.

(c) When we want to compare input lines/fields to the pattern.?

(d) When we want to perform an action on the matched file.

Syntax:

awk options 'selection _criteria {action }' input-file > output-file        

Options:??

-f program-file : Reads the AWK program source from the file 
                  program-file, instead of from the 
                  first command line argument.
-F fs            : Use fs for the input field separator        

Lets see some of the sample Commands?

Example:?

Consider the following text file as the input file for all cases below:?

$cat > employee.txt 
Ajay manager account 45000
Sunil clerk account 25000
varun manager sales 50000
amit manager account 47000
tarun peon sales 15000
deepak clerk sales 23000
sunil peon sales 13000
satvik director purchase 80000         

1. Default behavior of Awk:?By default Awk prints every line of data from the specified file.??

$ awk '{print}' employee.txt        

Output:??

ajay manager account 45000
sunil clerk account 25000
varun manager sales 50000
amit manager account 47000
tarun peon sales 15000
deepak clerk sales 23000
sunil peon sales 13000
satvik director purchase 80000         

In the above example, no pattern is given. So the actions are applicable to all the lines. Action print without any argument prints the whole line by default, so it prints all the lines of the file without failure.?

2. Print the lines which match the given pattern.?

$ awk '/manager/ {print}' employee.txt         

Output:??

ajay manager account 45000
varun manager sales 50000
amit manager account 47000         

In the above example, the awk command prints all the line which matches with the ‘manager’.?

3. Splitting a Line Into Fields:?For each record i.e line, the awk command splits the record delimited by whitespace character by default and stores it in the $n variables. If the line has 4 words, it will be stored in $1, $2, $3, and $4 respectively. Also, $0 represents the whole line.??

$ awk '{print $1,$4}' employee.txt         

Output:??

ajay 45000
sunil 25000
varun 50000
amit 47000
tarun 15000
deepak 23000
sunil 13000
satvik 80000         

In the above example, $1 and $4 represent the Name and Salary fields respectively.

要查看或添加评论,请登录

abhinav Ashok kumar的更多文章

社区洞察

其他会员也浏览了