awk
This is an old revision of the document!
Sample AWK questions
- How to run awk command specified in a file?
awk -f filename
- Write a command to print the squares of numbers from 1 to 10 using awk command
awk 'BEGIN { for(i=1;i⇐10;i++) {print “square of”,i,“is”,i*i;}}
'
- Write a command to find the sum of bytes (size of file) of all files in a directory.
ls -l | awk 'BEGIN {sum=0} {sum = sum + $5} END {print sum}
'
- In the text file, some lines are delimited by colon and some are delimited by space. Write a command to print the third field of each line.
awk '{ if( $0 ~ /:/ ) { FS=“:”; } else { FS =“ ”; } print $3 }' filename
- Write a command to print the line number before each line?
awk '{print NR, $0}' filename
- Write a command to print the second and third line of a file without using NR.
awk 'BEGIN {RS=“”;FS=“\n”} {print $2,$3}' filename
- Write a command to print zero byte size files?
ls -l | awk '/^-/ {if ($5 !=0 ) print $9 }
'
- Write a command to rename the files in a directory with “_new” as postfix?
ls -F | awk '{print “mv “$1” “$1”.new”}' | sh
- Write a command to find the total number of lines in a file without using NR
awk 'BEGIN {sum=0} {sum=sum+1} END {print sum}' filename
Another way to print the number of lines is by using the NR. The command is
awk 'END{print NR}' filename
awk.1406867127.txt.gz · Last modified: 2014/08/01 04:25 by pawluk