4

We have the following output

cat gh.log

 machine              status               
 =============================================================
 connection_ght 400
 pach_po 72
 timeout 311
 ping_agent 119675
 rt_machine 231
 ginco_snmp   14
 .
 .
 .
 .

How to print the output like this by using printf

 machine              status               
 =============================================================
 connection_ght..... 400
 pach_po............ 72
 timeout............ 311
 ping_agent......... 119675
 rt_machine......... 231
 ginco_snmp ........ 14
  • 1
    This isn't a job for the shell and printf. Use a proper text-processing tool (e.g. awk). – don_crissti Jan 2 '18 at 16:17
7

Add the line of dots to the string that goes to printf, and have printf cut it to length. In shell:

$ for x in a bbb cccccc ; do 
    printf '%.20s %s\n' "$x.................................." blah;
  done
a................... blah
bbb................. blah
cccccc.............. blah

In awk:

$ printf "a 123\nbbbbbb 456\n" | 
    awk '{printf "%.20s %s\n", $1 ".....................", $2}'
a................... 123
bbbbbb.............. 456

In %N.Ms, N is the minimum width for the field, M the maximum.


To convert that first snippet to the second, you could do something like this:

$ awk 'NR <= 2 {print; next} {printf "%.20s %s\n", $1 ".....................", $2}' < gh.log
machine              status               
=============================================================
connection_ght...... 400
pach_po............. 72
etc.

The NR <= 2 {print; next} condition passes the first two lines through as-is, the rest is converted as above. Note that this assumes there are no other columns etc. Adapt to taste.


printf can take the field width as a separate parameter, if you put a * in its place, so we could also do this:

printf '%s%.*s %s\n' "$x" $(( 20 - ${#x} )) "................................" blah

(${#x} is the length of the variable x.) That would keep the string and the filler separated, but is perhaps a bit too unwieldy for shell or awk. It might be useful in C code where the memory management for string manipulations is more annoying to do.

  • but how to implement your code to my output example – jango Jan 2 '18 at 16:15
  • @jango, oh sorry, I thought you meant you had a program that produces the output and wanted to modify it. It should be doable to process the text you presented with awk like that, edited. – ilkkachu Jan 2 '18 at 16:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.