Awk: Difference between revisions

From Leo's Notes
This page was last edited on 13 December 2013, at 18:06.
Created page with " == 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 ..."
 
No edit summary
Line 13: Line 13:
To find the number of lines up until 'cake', do:
To find the number of lines up until 'cake', do:
  cat list.txt | awk 'BEGIN { n = 0 } /cake/ { print n; next } { n++ }'
  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:
<syntaxhighlight lang="bash" line start="1" enclose="div">
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 \
  }'
</syntaxhighlight >


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

Revision as of 18:06, 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 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 \ 
   }'