Padding characters in printf

bash printf padding
printf repeat character
printf b
bash printf tab character
printf scientific notation
shell printf zero padding
bash: printf table
ksh printf examples

I am writing a bash shell script to display if a process is running or not.

So far, I got this:

printf "%-50s %s\n" $PROC_NAME [UP]

The code gives me this output:

JBoss                                              [DOWN]

GlassFish                                          [UP]

verylongprocessname                                [UP]

I want to pad the gap between the two fields with a '-' or '*' to make it more readable. How do I do that without disturbing the alignment of the fields?

The output I want is:

JBoss -------------------------------------------  [DOWN]

GlassFish ---------------------------------------  [UP]

verylongprocessname -----------------------------  [UP]

Pure Bash, no external utilities

This demonstration does full justification, but you can just omit subtracting the length of the second string if you want ragged-right lines.

pad=$(printf '%0.1s' "-"{1..60})
for string1 in a aa aaaa aaaaaaaa
     printf '%s' "$string1"
     printf '%*.*s' 0 $((padlength - ${#string1} - ${#string2} )) "$pad"
     printf '%s\n' "$string2"

Unfortunately, in that technique, the length of the pad string has to be hardcoded to be longer than the longest one you think you'll need, but the padlength can be a variable as shown. However, you can replace the first line with these three to be able to use a variable for the length of the pad:

pad=$(printf '%*s' "$padlimit")
pad=${pad// /-}

So the pad (padlimit and padlength) could be based on terminal width ($COLUMNS) or computed from the length of the longest data string.



Without subtracting the length of the second string:


The first line could instead be the equivalent (similar to sprintf):

printf -v pad '%0.1s' "-"{1..60}

or similarly for the more dynamic technique:

printf -v pad '%*s' "$padlimit"

You can do the printing all on one line if you prefer:

printf '%s%*.*s%s\n' "$string1" 0 $((padlength - ${#string1} - ${#string2} )) "$pad" "$string2"

%s is a string formatting specification. Zero padding is only defined to exist for numeric conversions: 0 For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversion specifiers, leading zeros (following any indication of sign or base) are used to pad to the field width Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more First 25 Users Free . Padding characters in printf. Ask Question Asked 8 years, 11 months ago. Active 9 months ago. Viewed 102k times

Pure Bash. Use the length of the value of 'PROC_NAME' as offset for the fixed string 'line':

printf "%s %s [UP]\n" $PROC_NAME "${line:${#PROC_NAME}}"
printf "%s %s [UP]\n" $PROC_NAME "${line:${#PROC_NAME}}"

This gives

abc ------------------------------------- [UP]
abcdef ---------------------------------- [UP]

Hi All, Is there any way to specify the number of spaces are padded before printing a number or character at runtime i.e for Exmaple: printf(""%Nd"",i); here the  printf("%4d",value); This statement ensures that the output for value is right-justified and at least four characters wide. If value is fewer than four characters wide, it’s padded with spaces on the left. That is, unless you stick a 0 in there:

Trivial (but working) solution:

echo -e "---------------------------- [UP]\r$PROC_NAME "

Notice that for shorter numbers, the result is padded out with leading spaces. For excessively long. Page 3. numbers there is no padding, and the full number is. printf padding with alternate character? pb. Nov 14 '05 # 1 Ben Pfaff. You will have to write your own code to do it. Nov 14 '05 # 2 Chris Torek. There is no standard way to do this. Reading email is like searching for food in the garbage, thanks Peter Nilsson. Im wanted to pad out blank

I think this is the simplest solution. Pure shell builtins, no inline math. It borrows from previous answers.

Just substrings and the ${#...} meta-variable.


# Strip excess padding from the right

B="A very long header"; echo "${A:0:-${#B}} $B"
B="shrt hdr"          ; echo "${A:0:-${#B}} $B"


[>----- A very long header
[>--------------- shrt hdr

# Strip excess padding from the left

B="A very long header"; echo "${A:${#B}} $B"
B="shrt hdr"          ; echo "${A:${#B}} $B"


-----<] A very long header
---------------<] shrt hdr

Im wanted to pad out blank spaces with a specific character instead of spaces or zeros, does C support that? printf("$%*d", '*', 5); // Not sure  This statement will reserve a row of 40 characters, print string at the end of the row (removing extra spaces such that the total row length is constant at 40). Same can be used for characters and integers as follows: printf("%*d", space, 10); printf("%*c", space, 'x');

There's no way to pad with anything but spaces using printf. You can use sed:

printf "%-50s@%s\n" $PROC_NAME [UP] | sed -e 's/ /-/g' -e 's/@/ /' -e 's/-/ /'

The c type specifier ignores padding and width. Warning. Attempting to printf("​%%c = '%c'\n", $c); // print the ascii character, same as chr() function printf("%%d​  Internally, printf () uses the java.util.Formatter class to parse the format string and generate the output. Additional format string options can be found in the Formatter Javadoc. 2.2. Conversion Characters. The conversion-character is required and determines how the argument is formatted. Conversion characters are only valid for certain data

Padding characters in printf - bash. There's no way to pad with anything but spaces using printf. You can use sed: printf "%-50s#%s\n" $PROC_NAME [UP]  For integer specifiers (d, i, o, u, x, X) − precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0.

Controlling integer width with printf. The %3d specifier is used with integers, and means a minimum width of three spaces, which, by default, will  printf format string refers to a control parameter used by a class of functions in the input/output libraries of C and many other programming languages.The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data (such

Is possible to print padded string in printf? Example If you want leading X characters in a 5 character field when you are printing a number that is 1 to 5 digits:. Padding characters in printf (7) Pure Bash, no external utilities. This demonstration does full justification, but you can just omit subtracting the length of the second string if you want ragged-right lines. pad=$(printf '%0.1s' "-"{1..60}) padlength=40

  • Could you explain a bit the printf '%*.*s' ... part ?
  • @EdouardLopez: The first asterisk is replaced by the zero in the argument list. The second asterisk is replaced by the result of the calculation in the second argument. The result, for the strings "aaaa" and "bbbbb", for example, is '%0.31s'. The string (the final argument) is truncated to the length specified after the dot. The zero prevents any space padding from being output. So 31 hyphens are output.
  • This page could help understand @Dennis Williamson answer:
  • {1..60} in need 60 as variable;... like "var=60"
  • @ReeganMiranda: The way this technique works is that you hard code the value to the largest one you need and use padlength to select the actual length to output.
  • The magic is the ${line:${#PROC_NAME}}, which uses bash substring extraction to start only return from a point of the variable line, which is set to start at the number of characters in PROC_NAME.
  • Note that this doesn't handle the case where PROC_NAME has spaces unless they are already escaped. You'll get one line with two tokens each and then [UP] for every two space-separated tokens in your variable and then a single line at the end with your line text minus the total length of your input string. So be careful, since this could lead to interesting and potentially insecure bugs if done in a complex script. Otherwise short and simple. :)
  • But only on a terminal. If the output is sent to a file it will be a mess.
  • so what you really expect from a trivial solution?!? full working also with output redirecting?!? ]:P
  • +1 There is an issue if PROC_NAME contains a dash - easily solved with an additional @: printf "%-50s@%s\n" ${PROC_NAME}@ [UP] | sed -e 's/ /-/g' -e 's/-@/ /' -e 's/@-/ /'
  • Strange, when I do printf 'x' {1..40} it only prints single x hmmm
  • @Krystian that's because you haven't copied the format: ` printf 'x%.0s' {1..40}` prints 40 xs
  • To avoid dash being interpreted as option double dash can be used to signal that the rest are non-option arguments printf -- "-%.0s" {1..40}