Friday, 2 August 2019

Linux - What is awk

The command awk allows searching data in a file and printing data on the console.  If a file contains multiple columns, then it is also possible to find data in specific columns. Furthermore, it helps tasks such as searching, conditional execution, updating and filtering.
awk  ‘{ print }’ file1.txt
The above command will display all the content in the file1.txt.  
Assume that the file1.txt file contains multiple columns.
awk   ‘{print $1}’ file1.txt
This command prints the first column of the file1.txt.  By default, the awk command considers a white space as the separator.
awk  ‘{print $1 “  ”  $3}’ file1.txt
The above command prints the first and the third column of the file1.txt with a space in between.
awk  ‘{print $1. $3}’ file1.txt
The above command will print the concatenation of first and the third column.
awk  ‘/example/ {print}’ file1.txt
The above command prints all the lines in the file1.txt file that contains the word example.
awk  ‘/ [0-9] / {print}’ file1.txt
The above command prints all the lines in the file1.txt file that contains numbers from 0 to 9.
awk  ‘/ ^ [0-9] / {print}’ file1.txt
This will print the lines in file1.txt that start with a number.
awk  ‘/   [0-9] $ / {print}’ file1.txt
This will print the lines in file1.txt that ends with a number.
It is also possible to check the conditionals as follows.
awk  ‘{ if ($1 ~  /123/ ) print}’ file1.txt
This will print the line if, the content starts with 123.
awk  ‘{ if ($2 ~  /[0-9] / ) print}’ file1.txt
This will print the lines in column two that start with a number.
Those are some examples of awk.
Overall, awk is a powerful command for processing and analyzing text files.

0 comments:

Post a Comment