-
Field Representations:
$0: Represents the entire line or record.$1: Represents the first column.$2: Represents the second column.$3: Represents the third column, and so on.
-
Default Separator:
- By default,
awktreats tab as the field separator. - For other separators (e.g.,
,in CSV files), use the-Foption orFSvariable.
- By default,
-
Processing Commands:
- To print specific fields or the entire line, use
printwith field variables. - Logical and relational operators with the
NRvariable (row number) allow row-based operations.
- To print specific fields or the entire line, use
awk '{print $1}' emp.txtOutput:
eno
100
200
300
400
500
awk '{print $1 " " $3}' emp.txtOutput:
eno esal
100 1000
200 2000
300 3000
400 4000
500 5000
Using , as the separator:
awk -F "," '{print $2 " " $4}' emp.csvOutput:
ename eaddr
Durga Mumbai
Bunny Hyderabad
Chinny Hyderabad
Vinny Chennai
Pinny Mumbai
awk 'NR != 1 {print $0}' FS="," emp.csvOutput:
100,Durga,1000,Mumbai
200,Bunny,2000,Hyderabad
300,Chinny,3000,Hyderabad
400,Vinny,4000,Chennai
500,Pinny,5000,Mumbai
-
NR(Number of Records) is useful for filtering specific rows. -
Examples:
awk 'NR==2 || NR==4 {print $0}' FS="," emp.csv
Output:
200,Bunny,2000,Hyderabad 400,Vinny,4000,Chennaiawk 'NR>2 && NR<5 {print $0}' FS=","
Output:
300,Chinny,3000,Hyderabad 400,Vinny,4000,Chennai
File: xy.txt
1.abc
2.def
3.ghi
4.jkl5.mno
Commands:
-
Entire Line:
awk '{print $0}' xy.txtOutput:
1.abc 2.def 3.ghi 4.jkl5.mno -
First Column:
awk '{print $1}' xy.txtOutput:
1.abc 2.def 3.ghi 4.jkl5.mno -
Second Column:
awk '{print $2}' xy.txtOutput: (Nothing is printed because there is no second column.)
- The default separator for
awkis tab. If you need to work with another separator (e.g., commas), you must specify it using-ForFS. awkassumes all input files are tabular.- Relational operators (
!=,<,>,<=, etc.) work effectively with theNRvariable for filtering rows.