1833874 Members
2396 Online
110063 Solutions
New Discussion

awk and printf

 
baiju_3
Esteemed Contributor

awk and printf

Hi ,

I am trying to format a log file .I need a aligned 4 column o/p .Sample of the log file is attached.

I am using cat sample.txt |awk -F"|" '{printf "%10s %-20s %20-s %20-s", $1,$2,$3,$4}'


But Its not able to format the o/p in columnvice.

Can you pls help.

Thanks
Good things Just Got better (Plz,not stolen from advertisement -:) )
6 REPLIES 6
A. Clay Stephenson
Acclaimed Contributor

Re: awk and printf

You are close; your main problem is lack of a linefeed ("\n") and a little better printf formatting is needed:

awk -F '|' '{printf("%-10.10s %-20.20s %-20.20s %-20.20s\n",$1,$2,$3,$4)}' sample.txt


If it ain't broke, I can fix that.
baiju_3
Esteemed Contributor

Re: awk and printf

Hi Clay Stephenson ,

\n I was using forgot to type .

It has not given me the required o/p .
Can you please try this on the sample.txt attached.

Thanks,
Baiju.
Good things Just Got better (Plz,not stolen from advertisement -:) )
A. Clay Stephenson
Acclaimed Contributor

Re: awk and printf

My version works perfectly for me using your input file. I do note that very few of your input lines have all four fields with non-whitespace values. It would help if you list a sample line of input followed by your desired output. You should also note that your attached file had CR's which I assume the original UNIX output did not have.
If it ain't broke, I can fix that.
baiju_3
Esteemed Contributor

Re: awk and printf


Control char might have added during copy paste to ITRC.

The o/p which I was looking for is attached .

Still no progress for me.
Good things Just Got better (Plz,not stolen from advertisement -:) )
A. Clay Stephenson
Acclaimed Contributor

Re: awk and printf

Well, I have no idea what your problem is but I spent about 4 minutes throwing together a script and tested it against your sample.txt.

Please see the attached file which contains both the script and the output.

After you yank out the script, chmod 777 my.sh and then
my.sh < sample.txt > out.txt
If it ain't broke, I can fix that.
Hein van den Heuvel
Honored Contributor

Re: awk and printf


You need to eat the spaces somehow.
The can be done with a replace in the 'code',
or they can be sucked into the ERE for the seperator. Try:

awk -F " *[|] *" '{printf "%10s %-20s %-20s %-20s\n", $1,$2,$3,$4}'


The ERE is
- a space followed by an asterix for zero or more spaces.
followed by
- a boxed in |. I had to do this to avoid the bar becoming an 'or'
followed y zero or more spaces.


Cheers,
Hein.