我在确定awk语句的语法错误方面遇到了一些困难。我的数据如下:
AAAA777
AAADMD
AAAEEE
AAALAWN
AAAMAN
AAA7777
我希望输出左对齐,填充到总共8个字符,最后加上几个附加组件。所需的输出如下:
AAAA777 ZC#8
AAADMD ZC#8
相反,我得到的是:
ZC#8777
ZC#8D
ZC#8E
ZC#8AWN
ZC#8N
ZC#8777
我的awk声明如下:
awk '{ printf "%-8.8s%2.2s%2s\n",$0,"ZC","#8" }' file.txt
似乎落后了,这不是所需的字符数。我做错了什么?
答案 0 :(得分:3)
问题似乎是您的文件有DOS / Windows行结尾。我创建了没有它们的file.txt,它工作正常:
$ awk '{ printf "%-8.8s%2.2s%2s\n",$0,"ZC","#8" }' file.txt
AAAA777 ZC#8
AAADMD ZC#8
AAAEEE ZC#8
AAALAWN ZC#8
AAAMAN ZC#8
AAA7777 ZC#8
但是,如果我将行结尾转换为DOS,那么我得到你看到的输出:
$ unix2dos <file.txt >file.dos
$ awk '{ printf "%-8.8s%2.2s%2s\n",$0,"ZC","#8" }' file.dos
ZC#8777
ZC#8D
ZC#8E
ZC#8AWN
ZC#8N
ZC#8777
除非您想保留DOS行结尾,否则直接的解决方案是使用任何常用工具删除它们,例如dos2unix
或tr
。
或者,使用awk的记录分隔符RS
来删除不需要的回车符:
$ awk -v RS='\r\n' '{ printf "%-8.8s%2.2s%2s\n",$0,"ZC","#8" }' file.dos
AAAA777 ZC#8
AAADMD ZC#8
AAAEEE ZC#8
AAALAWN ZC#8
AAAMAN ZC#8
AAA7777 ZC#8