Awk

From Leo's Notes
Revision as of 18:06, 13 December 2013 by Leo (talk | contribs)
This page was last edited on 13 December 2013, at 18:06.

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 bytes. 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("B KB MB GB TB PB", type) \ 
   } \ 
   { \ 
      y = 0; \                                                                                                  
      x = $1; \ 
      for (i = 5; y < 1 ; i--) \ 
         y = x / (2 ** (10 * i)); \ 
      print y type[i+2]" "$2 \ 
   }'