How to pad string with zeroes & right-justify in bash using sed
Pad any string using this sed command:
pad_string_zeroes_sed.sh
sed -e :a -e 's/^.\{1,3\}$/0&/;ta'This pads every string to length 4, usage example:
example.sh
$ echo x | sed -e :a -e 's/^.\{1,3\}$/0&/;ta'
000xIn case you want to pad to a different length, replace 3 in the script by (your desired length - 1).
You can also use a bash function like this:
example.sh
# Zero pad to length 4, right-justified
function zero_pad4 { echo $1 | sed -e :a -e 's/^.\{1,3\}$/0&/;ta' ; }Usage example:
example.sh
$ zero_pad4 1x
001xOriginal source, modified: The Unix School
Check out similar posts by category:
Shell
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow