banner

For a list of BASHing data 2 blog posts see the index page.    RSS


How to add trailing spaces and zeroes

It's pretty easy to add leading spaces or zeroes with one of the versions of printf. Below I tell the BASH builtin printf to add 3 leading spaces or 3 leading zeroes to the string "123". Repeating the first command, I've made the spaces visible with the spacevis function.

leading

These commands work because I've specified that the width of the output should be 6 characters (%6). Since the string is only 3 characters, printf expands the string by adding 3 spaces to the left.

With numeric strings like "123", I can left-pad with zero by putting a "0" before the width option (%06). However, this only applies if I specify a numeric string with "d" (%06d), not with text strings (%06s); see the last command, above.

Leading spaces and zeroes are a kind of right-justifying. How about left-justifying? Can you add trailing spaces and zeroes just as easily?

Spaces yes, zeroes no. Putting a hyphen in front of the width specification means "left-justify", so you can add as many trailing spaces as you require to make up to the specified width:

trailing1

Doing that for a list of strings can be done either with a while loop or more simply with AWK:

trailing2

There's no "trailing zeroes" option for printf, though, maybe because that's the same as multiplying by 10, 100, 1000 etc. To get trailing zeroes you can replace spaces (added by left-justifying) with the zero character, for example with sed:

trailing3

The replacement can also be done in one step with AWK, paying careful attention to the syntax:

trailing4

Here the replacement of spaces with zeroes is done by GNU AWK's gensub function, and the target string for replacement is the output of sprintf, which works just like printf but doesn't print its output.


Next post:
2025-05-02   csvlens: a delimited text file viewer for the terminal


Last update: 2025-04-25
The blog posts on this website are licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License