Chinaunix

标题: 一件诡异的事情,无法理解,请大神指点 [打印本页]

作者: bikkuri    时间: 2020-03-09 05:11
标题: 一件诡异的事情,无法理解,请大神指点
本帖最后由 bikkuri 于 2020-03-09 05:28 编辑

大家好!
我有一个问题向大家请教。
有a和b两个文本文件,两者的区别仅仅在于第二行中的最后一个字母,一个是小写字母o,一个是大写字母A。
[root@betactvdh:/tmp]# cat a
1
2% o
3
4
5
6
[root@betactvdh:/tmp]# cat b
1
2% A
3
4
5
6
[root@betactvdh:/tmp]# diff a b
2c2
< 2% o
---
> 2% A[root@betactvdh:/tmp]# hexdump -C a
00000000  31 0a 32 25 20 6f 0a 33  0a 34 0a 35 0a 36 0a     |1.2% o.3.4.5.6.|
0000000f
[root@betactvdh:/tmp]# hexdump -C b
00000000  31 0a 32 25 20 41 0a 33  0a 34 0a 35 0a 36 0a     |1.2% A.3.4.5.6.|
0000000f
[root@betactvdh:/tmp]#



然后我用同一条awk命令将6行的文本折叠成两行,其中对b文件可以得到期望的结果,但是对a文件的操作却失败了!
[root@betactvdh:/tmp]# cat a|awk '{for(i>0;i<=NR;i++)a=$0}END{for(j=0;3*j+1<i;j++){printf"|";for(k=1;k<=3;k++)printf a[3*j+k]"|";printf"\n"}}'
|1|awk: cmd. line:1: (FILENAME=- FNR=6) fatal: not enough arguments to satisfy format string
        `2% o|'
           ^ ran out for this one
[root@betactvdh:/tmp]# cat b|awk '{for(i>0;i<=NR;i++)a=$0}END{for(j=0;3*j+1<i;j++){printf"|";for(k=1;k<=3;k++)printf a[3*j+k]"|";printf"\n"}}'
|1|2% A|3|
|4|5|6|

  1. awk '{for(i>0;i<=NR;i++)a[i]=$0}END{for(j=0;3*j+1<i;j++){printf"|";for(k=1;k<=3;k++)printf a[3*j+k]"|";printf"\n"}}'
复制代码



awk的版本是gawk 4.0.2,算是比较高的版本。
[root@betactvdh:/tmp]# awk --version
GNU Awk 4.0.2
Copyright (C) 1989, 1991-2012 Free Software Foundation.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/.
[root@betactvdh:/tmp]#

请问为什么会出现这种情况呢?

[attach]712581[/attach]

谢谢大家!


awk_issue.png (45.65 KB, 下载次数: 95)

awk_issue.png

作者: cfwyy    时间: 2020-03-09 10:15
1.  一点也不诡义,问题出在在printf函数,你再去翻翻该函数的用法,其实错误提示已经给你信息了... format string...就是在格式化字符的时候出错了。printf函数格式化符 百分号后面的一些字符是有格式化意义的,碰巧让你碰到一个有意义,一个无意义。
你写的printf部分改成
  1. printf("%s|",a[3*j+k])
复制代码
即可。
2.  如果只是对你的两个文件达要你要的结果,我会这么写:
  1. awk '{a[NR]=$0}END{for(i=1;i<=NR;i++){printf("|%s",a[i]);if(i%3==0)printf("|\n")}}' file
复制代码

作者: bikkuri    时间: 2020-03-09 12:56
回复 2# cfwyy

谢谢您的指点!




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2