Whilst there are many tools for text formatting, printf is unique and universal.
Learn all about printf in Bash to format your text just the right way!
To have the same tool available in Bash is of great benefit.
printf allows you to control and produce complex output formats, just the way you want it.
No problem, printf can do it and much more.
It could also output the text to a specific column on the screen, etc.
Shutterstock/gilangtristiano
Let’s have a look at these first.
For a full list of available interpreted sequences, seeman printf.
The most common ones arenfor newline,tfor tab and\for a backslash.
In the options format above we also saw how we can specify flags.
We also inserted a space (as a flag) in between%and the width definition.
This led to the negative number inVAR1to be printed using a negative sign.
So how can we ensure that we have leading zeros or spaces, while still having a specific length?
The output indeed yields leading zeroes, up to the defined length.
This remains the same even if we would use leading zeroes.
It also remains the same if no length is specified.
The usability of the space flag may thus in some cases (negative numbers) be limited.
Conclusion
Using printf from within Bash scripts or at the command line can yield clear well-defined output.
Enjoy printing well-formatted data with printf!