1833777 Members
2153 Online
110063 Solutions
New Discussion

Problems with PRINTF...

 
SOLVED
Go to solution
Mike Button
Occasional Contributor

Problems with PRINTF...

Hey All,

I have a text document that has 7 columns. The document is a result of echo'ing a group of variables. The document has up to 100 lines, but when I view the data it is not aligned great. It is all jagged and over the place, making it hard to view. Someone has told me that I can use PRINTF to specify column widths and tab delimeters to clean things up, but after revewing the man pages on PRINTF I am lost. Is there anyone that can help me??

Thanks,
Mike Button

P.S. The columns are like this.
1 -> string
2 - 7 -> numeric (1 -5 max per column)
5 REPLIES 5
John Poff
Honored Contributor
Solution

Re: Problems with PRINTF...

Hi Mike,

One way to do it is with awk. With printf, you specify the type of field and the length of the field. For strings, you use the %s parameter. For numbers, you have several choices, but you'll probably want the %d parameter for decimal integers. Something like this might work:

awk '{printf("%20s %6d %6d %6d %6d %6d %6d\n", $1, $2, $3, $4, $5, $6, $7)}' myfile

The \n adds a new line. You can also use \t to insert tab characters, but specifying the field lengths usually makes things print pretty cleanly without any tabs.

I know you can use printf in shell scripts but I haven't played with it. The printf in awk is pretty much like the one in C and Perl, and it gets the job done for me.

JP
Mike Button
Occasional Contributor

Re: Problems with PRINTF...

Thanks for the suggestion, but after trying it, why I get is one line from my document and then one line that looks like this, 20s %6d %6d %6d %6d %6d %6d

Any suggestion, here is my command:

awk '{print ("20s %6d %6d %6d %6d %6d %6d\n", $1, $2, $3, $4, $5, $6, $7)}' myfile >myfile2
John Poff
Honored Contributor

Re: Problems with PRINTF...

Hi,

You typed 'print' instead of 'printf', and your first parameter should be %20s instead of just 20s. Try it that way and see what you get.

JP
Mike Button
Occasional Contributor

Re: Problems with PRINTF...

Ever have one of those days...Thanks a lot...Things look great.

Mike
susan gregory_1
Valued Contributor

Re: Problems with PRINTF...

Hi Mike,
You don't have to do that in awk, you can do the same thing in your C program.

printf("%20s%7d\n", mystring, myint);

will put the string right justified starting at the 20th column and the integer at right justified at the 17th column.