获取Ascii代码?

时间:2012-04-24 09:36:26

标签: awk

要检索文件第13列的所有承租人的ascii代码,我写这个脚本

awk -v ch="'" '{
for (i=1;i<=length(substr($13,6,length($13)));i++)
{cmd = printf \"%d\\n\" \"" ch substr(substr($13,6,length($13)),i,1) "\"" cmd | getline output close(cmd) ;
Number= Number " " output 
}
 print Number ; Number="" 
}' ~/a.test

但它不能以正确的方式运作!我的意思是它运作良好一段时间然后产生奇怪的结果!? 例如,对于此输入(假设它是第13列)

  

CQ:Z:%8 %%%% 0 %%%% 9 %%%%:%%%%%%%%%%%%%%%%%%

我必须得到这个

  

37 56 37 37 37 37 48 37 37 37 37 57 37 37 37 37 58 37 37 37 37 ...............

但我有这个

  

37 56 37 37 37 37 48 48 48 48 48 57 57 57 57 57 58 58 58 58 58 ...............

正如你所看到的,第一个错误计算出现在字符“0”之后(结果为48)。

您知道我的代码的哪一部分对此错误负责吗?!

2 个答案:

答案 0 :(得分:2)

试试这个:

awk '{
    str = substr($13, 6)
    for (i=1; i<=length(str); i++) {
      cmd = "printf %d \42\47" substr(str, i, 1) "\42"    
      cmd | getline output
      close(cmd)
      Number= Number " " output 
    }
   print Number 
   Number="" 
  }' ~/a.test

\42"\47',因此每个printf %d "'${char}"在shell中运行${char},这会触发评估为带有POSIX扩展名的C常量,指示POSIX printf definition's §Extended Description的最后一个项目符号中指出的数值。

N.B。格式很重要! 除非您确切知道自己在做什么,否则不要试图挤压代码!

一个纯粹的 awk 解决方案(我直接从手册中获取了 ord / chr 函数):

printf '%s\n' 'CQ:Z:%8%%%%0%%%%9%%%%:%%%%%%%%%%%%%%%%%%'|
  awk 'BEGIN { _ord_init() }
    {
      str = substr($0, 6)
      for (i = 0; ++i <= length(str);)
        printf "%s", (ord(substr(str, i, 1)) (i < length(str) ? OFS : ORS))
      }
    func _ord_init(    low, high, i, t) {
      low = sprintf("%c", 7) # BEL is ascii 7
      if (low == "\a") {     # regular ascii
        low = 0
        high = 127
       } 
      else if (sprintf("%c", 128 + 7) == "\a") {
        # ascii, mark parity
        low = 128
        high = 255
        } 
      else {                  # ebcdic(!)
        low = 0
        high = 255
       }

    for (i = low; i <= high; i++) { 
      t = sprintf("%c", i)
      _ord_[t] = i
       }
    }

  func ord(str,    c) {
    # only first character is of interest
    c = substr(str, 1, 1)
    return _ord_[c]
    }

  func chr(c) {
    # force c to be numeric by adding 0
    return sprintf("%c", c + 0)
    }'

答案 1 :(得分:0)

这可能对您有用:

awk -vSQ="'" -vDQ='"' '{args=space="";n=split($13,a,"");for(i=1;i<=n;i++){args=args space DQ SQ a[i] DQ;format=format space "%d";space=" "};format=DQ format "\\n" DQ;system("printf " format " " args)}'