The largest number of digits in the shown example is 7. With input file nums.txt
perl -ne 'printf("%07d\n", $_)' nums.txt > padded_nums.txt
> cat padded_nums.txt
0000235
0000025
0000001
0963258
0000045
1356924
If the number of digits of the largest number is in fact not known, a bit more is needed
perl -ne 'push @l, $_; }{ $lm = length( (sort {$b <=> $a} @l)[0] ); printf "%0${lm}d\n", $_ for @l' nums.txt
Prints the same.
As noted by glenn jackman in comments, using the List::Util
module gives us a maximum in O(n)
, as opposed to sort
with O(nlog(n))
. This does load a module, albeit it being very light.
perl -MList::Util=max -ne ' ... $lm = length(max @l); ...'
Per request in a comment, here is how to pad numbers in shell, copied from this post
for i in $(seq -f "%05g" 10 15)
do
echo $i
done
Also, in the same answer, a single printf
formatting is offered
$ i=99
$ printf "%05d\n" $i
00099
Note the difference above, of 05g
vs 05d
between seq
and printf
.
Here is a way to process the whole file with bash
, used from this post.
while read p; do
printf "%07d\n" $p
done < nums.txt
Finally, use size=${#var}
to find the length of a string in bash
, if the length of the largest number is not known. This requires two passes over data, to find the max length and then to print with it.
These examples are for bash
but tcsh
has all these facilities as well, used with different syntax.