LoginSignup
0
0

More than 1 year has passed since last update.

awkでカンマ編集

Last updated at Posted at 2021-08-22

大昔、テキスト処理で数値のカンマ編集を実装(笑)する関数を書いていた記憶があったので、掘り起こし。たまたま必要になったものでwww


ykishi@dezembro /tmp % cat foo.sh 
#!/bin/sh

awk 'BEGIN{
  print comma(1234567890);
  print comma(123456789);
  print comma(12345678);
  print comma(1234567);
}
function comma(val) {
  a = val + "";
  len = length(a);
  s = len%3;
  from = len;
  to = from - s;
  buf = "";
  while( from > 0 ){
    if( from != to ){
      if( buf == "" ){
        buf =  substr(a, len - from + 1, from - to) + "";
      } else {
        buf = sprintf("%s,%s", buf, substr(a, len - from + 1, from - to) )
      }
    }
    from = to
    to -= 3;
  }
  return buf;
}'

ykishi@dezembro /tmp % ./foo.sh 
1,234,567,890
123,456,789
12,345,678
1,234,567
ykishi@dezembro /tmp % 
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0