write an awk script ‘list_sizes.awk’ that prints the size of every element in th
ID: 3723645 • Letter: W
Question
write an awk script ‘list_sizes.awk’ that prints the size of every element in the free list, in order, after each Free or Alloc operation. Your program should act like this:
$ awk -f list_sizes.awk malloc-out.txt | head
99
1 99
1 92
1 7 92
1 2 92
1 2 84
1 2 8 84
1 5 2 8 84
5 2 8 84
2 8 84
Hint: you can use ‘printf’ and loops in awk programs. In both cases the syntax is similar to C. Here is an example of an awk program with a loop:
{ n = $1
for (i=0; i < n; i++) {
printf(“%s ”, $(2+i))
}
}
This program assigns the value in field 1 to variable n, then prints fields 2, 3, 4 up to field 2 + n - 1.
I can provide malloc-out.txt if needed!!!!!!
malloc-out.txt:
https://drive.google.com/file/d/17WMZ9mwG_Wr2YtOwdnFfLo9gGBLHM6HL/view
Explanation / Answer
AWK COMMAND:
awk 'BEGIN{FS=" |:";} {for(i=1;i<NF;i++){if( $i ~ /sz/)printf "%s ",$(i+1)};printf " "}' malloc-out.txt
This is a single line command to extract the elements. You can put the awk operations in an awk file and perform the execution.
EXPLANATION:
BEGIN block is for any declaration or initalization of variables before the processing begins. It helps us to create header or title required for the result which can be specified in this block. I have initialized the Field Separator (FS) here. I have declared multiple separators separated by "|". The delimiters which I have used here are space and ":". You can even use -f option to specify this details if you do not need a BEGIN block.
Next is a loop to check for data from the first column to the last column ( which is specified as NF - built-in variable which gives the totoal number of fields processed)
Next is the if statement where I am checking for the column containing 'sz' data. Once that column is found I am printing the column next to 'sz' as per the requirement.
This command works and is verified for the given input
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.