Awk cheatsheet

From Lolly's Wiki
Revision as of 10:20, 20 October 2016 by Lollypop (talk | contribs)
Jump to navigationJump to search

Cheatsheet

Functions

Binary to decimal

function b2d(bin){
  len=length(bin);
  for(i=1;i<=len;i++){
    dec+=substr(bin,i,1)*2^(len-i);
  }
  return dec;
}

Sort words inside braces (gawk)

Written for beautifying lines like

GRANT SELECT (account_id, user, enable_imap, fk_domain_id, enable_virusscan, max_msg_size, from_authuser_only, id, time_start, changed_by, enable_spamblocker, onhold, time_end, archive, mailbox_quota) ON `mail_db`.`mail_account` TO 'user'@'172.16.16.16'
function inner_brace_sort (rest) {
  sorted="";
  while( match(rest,/\([^\)]+/) ) {
    sorted=sprintf("%s%s", sorted, substr(rest, 1, RSTART));
    inner=substr(rest, RSTART+1, RLENGTH-1); 
    split(inner, inner_a, /,[ ]*/);
    asort(inner_a);
    inner_l=length(inner_a);
    for(i=1; i<=inner_l; i++) {
      sorted=sprintf("%s%s", sorted, inner_a[i]);
      if(i<inner_l) sorted=sorted""sprintf(", ");
    }
    sorted=sprintf("%s)", sorted);
    rest=substr(rest,RSTART+RLENGTH+1,length(rest));
  }
  return sorted""rest;
}