如何用awk列出所有非ascii字节?

时间:2017-04-11 04:51:05

标签: bash awk

这是google drive上的测试文件。

sample :test file

我想列出测试文件中带有awk的\ x00- \ x7f以外的所有字节非ascii字节。
\ x00- \ x7f之外有12个字节。

这是我的尝试。

awk 'BEGIN{FS=""}{for(i=1;i<=NF;++i)if($i~/[^\x00-\x7f]/)print i,$i}'  test
146 “
148 ”
181 “
184 ”

awk 'BEGIN{FS=""}{for(i=1;i<=NF;++i)if($i~/[^\x00-\x7f]/)printf("%d %x \n", i,$i)}'  test
146 0 
148 0 
181 0 
184 0

失败,如何按以下格式列出文件中的所有12个字节。

146  e2
147  80
148  9c
150  e2
151  80
152  9d
185  e2
186  80
187  9c
190  e2
191  80
192  9d

test file in hex format with xxd test command

export LC_ALL=C
awk 'BEGIN{FS=""}{for(i=1;i<=NF;++i)if($i~/[^\x00-\x7f]/)printf("%d %c\n",i,$i)}'  test
146 
147 �
148 �
150 
151 �
152 �
185 
186 �
187 �
190 
191 �
192 �

如何修复我的代码?

1 个答案:

答案 0 :(得分:1)

我在UTF8 shell中:

$ locale
LANG=en_US.UTF-8
...

首先:

$ export LC_ALL=C

然后:

$ awk -F '' '                         # split record in fields
BEGIN { for(n=0;n<256;n++)            # iterate all values
            ord[sprintf("%c",n)]=n }  # make a hash ord[char]=n
      { for(i=1;i<=NF;i++)            # iterate all fields
            if(ord[$i]>127)           # beyond 7f
                print ord[$i] }       # print n (value)
' test

输出:

226
128
156
226
128
157
226
128
156
226
128
157

以十六进制表示:

e2
80
9c
...