To print 2 cloumns
ll | awk {'print $2,$3'}
1. Awk FS : Input field separator variable.
syntax: awk -F 'FS' 'commands' inputfilename
cat /etc/passwd |awk -F : {'print $1'}
OR
awk -F : {'print $1'} < /etc/passwd
EXAMPLES:
test file:
[root@drbd1 korion]# cat emplyeet.xt
100 Thomas Manager Sales $5,000
200 Jason Developer Technology $5,500
300 Sanjay Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000
a) To print all the contents
awk {'print ;'}
b) Print the lines which matches with the pattern.
awk can accept any number of patterns, but each pattern should be in a new line
awk '/Thomas/
> /Nisha/'
c)Print only specific field.
cat emplyeet.txt | awk {'print $2'}
d)Initialization and Final Action
Syntax:
BEGIN { Actions}
{ACTION} # Action for everyline in a file
END { Actions }
example:
awk 'BEGIN {print "Name\tDesignation\tDepartment\tSalary";} {print $2,"\t",$3,"\t",$4,"\t",$NF;} END{print "Report Generated\n--------------";}'
[root@drbd1 korion]# awk 'BEGIN {print "Name\tDesignation\tDepartment\tSalary";} {print $2,"\t",$3,"\t",$4,"\t",$NF;} END{print "Report Generated\n--------------";}'
Thomas Manager Sales $5,000
Jason Developer Technology $5,500
Sanjay Sysadmin Technology $7,000
Nisha Manager Marketing $9,500
Randy DBA Technology $6,000
Report Generated
=========================================================
exapmple2:
To print emplyee details having id >200
awk '$1 >200'
[root@drbd1 korion]# awk '$1 >200'
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000
[root@drbd1 korion]#
=========================================================
example 3:
Print the list of employees in Technology department
awk '/Technology/'
[root@drbd1 korion]# awk '/Technology/'
300 Sanjay Sysadmin Technology $7,000
500 Randy DBA Technology $6,000
OR
[root@drbd1 korion]# awk '$4 ~/Technology/'
300 Sanjay Sysadmin Technology $7,000
500 Randy DBA Technology $6,000
[root@drbd1 korion]#
example 4: Print number of emplyees in technology department
awk 'BEGIN {count=0;} $4 ~/Marketing/ {count++;} END {print "The number of emps in Marketing dept is =",count;}'
[root@drbd1 korion]# awk 'BEGIN {count=0;} $4 ~/Marketing/ {count++;} END {print "The number of emps in Marketing dept is =",count;}'
IMPORTANT:
To print strings start with a particular letter
EXAMPLE: print emplyee names which starts with T
awk '$2 ~ /^T/'
[root@drbd1 korion]# awk '$2 ~ /^T/'
600 Tom Admin Marketing $9,000
[root@drbd1 korion]#
EXAMPLE: print emplyee names which not starts with T
awk '$2 !~ /^T/'
[root@drbd1 korion]# awk '$2 !~ /^T/'
300 Sanjay Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000
[root@drbd1 korion]#
=====================================================
awk script to print directories
ll | awk '$1 ~ /^drwxr/'
awk script to print files in a directory
ll | awk '$1 !~ /^drwxr/'
=====================================================
No comments:
Post a Comment