Pad any string using this sed command:
sed -e :a -e 's/^.\{1,3\}$/0&/;ta'
This pads every string to length 4, usage example:
$ echo x | sed -e :a -e 's/^.\{1,3\}$/0&/;ta' 000x
In 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:
# Zero pad to length 4, right-justified function zero_pad4 { echo $1 | sed -e :a -e 's/^.\{1,3\}$/0&/;ta' ; }
Usage example:
$ zero_pad4 1x 001x
Original source, modified: The Unix School