Thread: Using printf

    #1
  1. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2004
    Posts
    512
    Rep Power
    50

    Using printf


    I have an echo command string operating inside of a while loop that provides me with the terminal output that I want, except that the field width for part of the output changes character length (example "This is 100% and this is 79%") consequentially the 100% changes less by 1 character and the 79% increases by 1 character, therefore adjusting the string length.
    My sample rate is 1 second which can make it difficult to follow the string as it accordions on the command line.
    I am sure I can stabilize this string with printf, but even though I have read and tried several things, I am not getting where I need to be.
    My echo code is
    Code:
    echo -en "\rCPU: $DIFF_USAGE% CPU AVERAGE: $AVG%  \b\b"
    I really need to format "$DIFF_USAGE%" and "$AVG%" output to 4 spaces - right justified.
    I hope someone can help me out.
    99% of what I have tried results in printf syntax errors.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2017
    Location
    Minnesota, USA
    Posts
    30
    Rep Power
    105
    A printf for what you're looking for would look like:

    printf( <filehandle> "\rCPU: %4d% and %4d%", $DIFF_USAGE, $AVG );

    %4d says to expect an integer number, and have it align to the right of a four character field.

    A working example:

    perl -e 'open(FILE, ">", "testfile.data"); printf( FILE "CPU: %4d% and %4d%\n", 25, 50 ); close(FILE);'

    Comments on this post

    • additude agrees : I'd give you points but its locked at 0
    • Axweildr agrees : For what additude said
    • ishnid agrees
  4. #3
  5. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2004
    Posts
    512
    Rep Power
    50
    Thanks for the help.

    That gave me what I needed to grasp printf and apply it to what I was doing.

    I ended up with
    Code:
      $C1="\033[1;32m"
      $C2="\033[1;32m"
      $C3="\033[0m"
    printf "\rCPU:$C1%4d%%$C3 CPU AVERAGE:$C2%4d%%$C3\t\t" "$DIFF_USAGE" "$AVG"
    Which adds some colors to it.

IMN logo majestic logo threadwatch logo seochat tools logo