Fill printf for lines at 0

Is there a way to replace the space character with 0 in the printf fingerprint for the field width

Code used

printf("%010s","this"); 

It doesn't seem to work for strings!

+6
source share
3 answers

Indeed, flag 0 only works for numerical conversions. You will have to do this manually:

 int print_padleftzeroes(const char *s, size_t width) { size_t n = strlen(s); if(width < n) return -1; while(width > n) { putchar('0'); width--; } fputs(s, stdout); return 0; } 
+8
source

What about

  test="ABCD" printf "%0$(expr 9 - ${#test})d%s" 0 $test 

which will give you what you need.

  ~:00000ABCD 

or do you want the padd with other numbers to just change

  printf "%0$(expr 9 - ${#test})d%s" 1 $test 

will provide you

  ~:11111ABCD 
+2
source

Try the following:

 printf("%010d%s", 0, "this"); 
-1
source

Source: https://habr.com/ru/post/905932/


All Articles