AWK –
select column data
-Search data in file and print data on console
-Find data of specific columns
-Format output data
-Used on file with bulk of data for searching, conditional executions, updating, filtering
Command 1
———
Print specific columns
awk '{print $1}' file.txt
by default TAB seperator
awk '{print $1 "--" $2}' file.txt
Command 2 –
———–
select all data from table
awk '{print $0}' tabfile.txt
Command 3-
———–
select columns from CSV
awk -F "," '{print $1}' commafile.txt
1.Seperating data using -F
awk -F "," '{print $1}' commafile.txt
2.Using variable (FS)
awk '{print $2}' FS="," commafile.txt
Command 4-
———-
Display content without displaying header of file
awk 'NR!=1{print $1 " " $2}' file.txt
NR is special variable
awk 'NR>2{print $1}' file.txt
awk 'NR>=2{print $2}' file.txt
Command 5-
———–
Saving results of AWK command to file
awk -F "," '{print $1 " " $2}' commafile.txt > result.txt
Command 6 –
———-
Row data filtering
awk -F "," '$1==1{print $1 "-"$2}' samplefile.txt
awk -F "," '$2=='sai'{print $1 "-" $2}' file.txt
awk -F "," '$3>1000{print $1 " " $2}' file.txt
Command 7 –
———–
Defining Row filtering with logical OR [ || ]
awk -F "," '$1==2 || $3==2000{print $1 " " $2}' commafile.txt
awk -F "," '$3>400 || $1==1{print $1 " " $2}' commafile.txt
Command 8 –
———–
Defining Row filering with logical AND [ && ]
awk -F "," '$2=='sai' && $3==100{print $0}' commafile.txt
Command 9 –
———-
Display records where we have specific string anywhere in row.
awk -F "|" '/sai/{print $0}' tabfile.txt
Display records that not having particular pattern
awk -F "|" '!/pra/{print $0}' tabfile.txt
Command 10 –
———
Display records where we have specific string in specific column.
awk -F "|" '$2-/sai/{print $0}' tabfile.txt
Display records not having the specific string in column
awk -F "|" '$2!-/sai/{print $0}' tabfile.txt