Awk: Difference between revisions

From Leo's Notes
This page was last edited on 13 December 2013, at 18:28.
Line 15: Line 15:


== Convert Number as Bytes to Human Readable Value ==
== Convert Number as Bytes to Human Readable Value ==
I wanted to sort size in reverse order, but in order to do that properly, the value from du needs to be in bytes. I also didn't want to run this through du again just to get the human readable value. So, I did this:
I wanted to sort size in reverse order, but in order to do that properly, the value from du needs to be in kilobytes. I also didn't want to run this through du again just to get the human readable value. So, I did this:


<syntaxhighlight lang="bash" line start="1" enclose="div">
<syntaxhighlight lang="bash" line start="1" enclose="div">
Line 30: Line 30:
       print y type[i+2]" "$2 \  
       print y type[i+2]" "$2 \  
   }'  
   }'  
</syntaxhighlight >
</syntaxhighlight>
 
If you want to count using bytes instead of kilobytes, just add K to the split function and replace i=4 with i=5.


[[Category:Linux]]
[[Category:Linux]]
[[Category:TipsnTricks]]
[[Category:TipsnTricks]]

Revision as of 18:28, 13 December 2013

Counting Lines Until Match

To print the number of lines before a match is found:

awk 'BEGIN { n = 0 } /PATTERN/ { print n; next } { n++ }'

Eg: Suppose I have a file with the contents:

leo
spoon
cake
fork

To find the number of lines up until 'cake', do:

cat list.txt | awk 'BEGIN { n = 0 } /cake/ { print n; next } { n++ }'

Convert Number as Bytes to Human Readable Value

I wanted to sort size in reverse order, but in order to do that properly, the value from du needs to be in kilobytes. I also didn't want to run this through du again just to get the human readable value. So, I did this:

du -s ./*/ ./*/*/ ./*/*/*/ \ 
   | sort -rn \ 
   | awk 'BEGIN { \ 
      split("KB MB GB TB PB", type) \ 
   } \ 
   { \ 
      y = 0; \                                                                                                  
      x = $1; \ 
      for (i = 4; y < 1 ; i--) \ 
         y = x / (2 ** (10 * i)); \ 
      print y type[i+2]" "$2 \ 
   }'

If you want to count using bytes instead of kilobytes, just add K to the split function and replace i=4 with i=5.