Monday, 29 November 2021

Unix awk command Part 2 -

 1. How to run the awk command specified in a file?

awk -f filename


2. 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}'


3. 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.txt


4. 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 a number is :",i,"is",i*i;}}'


5. Write a command to print the line number before each line?

awk '{print NR, $0}' filename.txt


6. 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.txt


7. Write a command to print the fields in a text file in reverse order?

awk 'BEGIN {ORS=""} { for(i=NF;i>0;i--) print $i," "; print "\n"}' filename


8. Another way to print the number of lines is by using the NR. The command is

awk 'END{print NR}' filename


9. 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


10. Write a command to rename the files in a directory with "_new" as postfix?

ls -F | awk '{print "mv "$1" "$1".new"}' | sh


11. Write a command to print zero byte size files?

ls -l | awk '/^-/ {if ($5 !=0 ) print $9 }'


No comments:

Post a Comment

how to create dml dynamically in Ab-initio

 $[ begin let int i = 0; let string(int) complete_list = "emp_nm,billable,age,designation,location"; let string(int) file_content ...