Awk syntax with printf - not desired format

289 views Asked by At

I'm having some difficulty determining where my syntax is wrong with an awk statement. My data looks like this:

AAAA777
AAADMD
AAAEEE
AAALAWN
AAAMAN
AAA7777


I want the output to be left justified, padded to 8 total characters, plus a couple of add-ons at the end. The desired output would look like:

AAAA777 ZC#8
AAADMD  ZC#8


Instead what I'm getting looks like:

ZC#8777
 ZC#8D
 ZC#8E
ZC#8AWN
 ZC#8N
ZC#8777


My awk statement looks like this:

awk '{ printf "%-8.8s%2.2s%2s\n",$0,"ZC","#8" }' file.txt

It seems backward and it's not the desired character count. What am I doing wrong?

1

There are 1 answers

1
John1024 On BEST ANSWER

The problem appears to be that your file has DOS/Windows line endings. I created file.txt without them and it worked fine:

$ 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

However, if I convert the line endings to DOS, then I get the output that you see:

$ 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

Unless you want to keep the DOS line endings, the straightforward solution is to remove them with any of the usual utilities, such as dos2unix or tr.

Alternatively, use awk's record separator, RS, to remove the unneeded carriage return:

$ 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