AWK stands for Aho, Weinberger, and Kernighan.
AWK command is a powerful command for processing text. It reads from input stream line by
line. It allows users to process and analyse data and produce output in different formats.
Below are few best questions on awk
Q. How to print contents of a file?
awk '{print $0}' [fileName]
Q. Print the lines which contain the word "pattern"?
awk '/pattern/' [fileName]
Q. Print the lines which does not contain the word "pattern"?
awk '!/pattern/' [fileName]
Q. Ignore first line and print all other lines?
awk 'NR>1{print $0}' [fileName]
Q. Print first 5 lines of a file?
awk '{if(NR <= 5){ print $0}}' [fileName]
Q. Print line 5 to line 10 of a file?
awk 'NR==5, NR==10{print $0}' [fileName]
Q. Print number of lines of a file?
awk 'END { print NR }' [fileName]
Q. How to pass variables to awk command?
awk -v variable="$ENVIRONMENT_VARIABLE" '{print variable}' [fileName]
Q. Print 4th column of a .csv file?
awk -F, '{print $4}' [fileName]
Q. Print last column of a .csv file?
awk -F, '{print $NF}' [fileName]
Q. Print second last column of a .csv file?
awk -F, '{print $(NF-1)}' [fileName]
Q. Find the sum of 1st column values in a .csv file?
awk '{SUM+=$1} END{print SUM}' [fileName]
Q. Write line number before each line of a file?
awk '{print NR,$0}' [fileName]
Q. Print the number of characters present each line?
awk '{print "Number of characters present in line no.",NR,"is",length($0)}' [fileName]
Q. Print total number of lines that contains the word "pattern"?
awk '/pattern/ {lines=lines+1} END{print lines}' [fileName]
Q. Print lines between the words "pattern1" and "pattern2"?
awk '/pattern1/,/pattern2/ {print $0}' [fileName]
Q. Remove spaces from the beginning of lines and then print the lines?
awk '{$1=$1;print}' [fileName]
Q. Replace the word "pattern1" with "pattern2" and then print the lines?
awk '{gsub("pattern1","pattern2"); print $0}' [fileName]
Q. Remove all the spaces from lines and then print the lines?
awk '{gsub("\ ",""); print $0}' [fileName]
Q. Print maximum number from 3rd column of a .csv?
awk -F, 'BEGIN{max=0} {if(max<int($3)){max=int($3);}} END{print max}' [fileName]
Q. Print non-empty lines of a file?
awk NF [fileName]
Q. Print lines which does not start with #?
awk '!/^#/' [fileName]
Q. Print non-empty lines which does not start with "#"?
awk '(!/^#/) && NF' [fileName]
Q. Print first 4 characters of 2nd column of a .csv file?
awk -F, '{print substr($2,1,4)}' [fileName]
Q. Print last 4 characters of 2nd last column of a .csv file?
awk -F, '{print substr($(NF-1),length($(NF-1))-3,4)}' [fileName]