Awk cheatsheet: Difference between revisions

From Lolly's Wiki
Jump to navigationJump to search
Line 23: Line 23:
This function:
This function:
<source lang=awk>
<source lang=awk>
function inner_brace_sort (rest) {
function inner_brace_sort (rest, delimiter) {
   sorted="";
   sorted="";
   while( match(rest,/\([^\)]+/) ) {
   while( match(rest,/\([^\)]+\)/) ) {
     sorted=sprintf("%s%s", sorted, substr(rest, 1, RSTART));
     sorted=sprintf("%s%s", sorted, substr(rest, 1, RSTART));
     inner=substr(rest, RSTART+1, RLENGTH-1);  
     inner=substr(rest, RSTART+1, RLENGTH-2);  
     split(inner, inner_a, /,[ ]*/);
     rest=substr(rest,RSTART+RLENGTH-1,length(rest));
     asort(inner_a);
     split(inner, inner_a, delimiter);
     inner_l=length(inner_a);
     inner_l=asort(inner_a, inner_s);
     for(i=1; i<=inner_l; i++) {
     for(i=1; i<=inner_l; i++) {
       sorted=sprintf("%s%s", sorted, inner_a[i]);
       sorted=sprintf("%s%s", sorted, inner_s[i]);
       if(i<inner_l) sorted=sorted""sprintf(", ");
       if(i<inner_l) sorted=sprintf("%s, ", sorted);
     }
     }
     sorted=sprintf("%s)", sorted);
     sorted=sprintf("%s", sorted);
    rest=substr(rest,RSTART+RLENGTH+1,length(rest));
   }
   }
   return sorted""rest;
   return sorted""rest;
}
}
</source>
</source>
Sorts the fields inside the braces alphabetically.
Sorts the fields inside the braces alphabetically and can be called like this:
<source lang=awk>
/\(/ {
  print inner_brace_sort($0, ",[ ]*");
}
</source>

Revision as of 09:36, 20 October 2016

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'

This function:

function inner_brace_sort (rest, delimiter) {
  sorted="";
  while( match(rest,/\([^\)]+\)/) ) {
    sorted=sprintf("%s%s", sorted, substr(rest, 1, RSTART));
    inner=substr(rest, RSTART+1, RLENGTH-2); 
    rest=substr(rest,RSTART+RLENGTH-1,length(rest));
    split(inner, inner_a, delimiter);
    inner_l=asort(inner_a, inner_s);
    for(i=1; i<=inner_l; i++) {
      sorted=sprintf("%s%s", sorted, inner_s[i]);
      if(i<inner_l) sorted=sprintf("%s, ", sorted);
    }
    sorted=sprintf("%s", sorted);
  }
  return sorted""rest;
}

Sorts the fields inside the braces alphabetically and can be called like this:

/\(/ {
  print inner_brace_sort($0, ",[ ]*");
}