I have a day-and-month text file like this:
day=
8
9
10
15
1
month=
3
6
7
10
1
I need to add "0" to lines, including only one-digit numbers. I need to write a loop to find a one-digit number in all the lines and add "0" to the left of the number like;
day=
03
06
07
10
01
month=
03
06
07
10
01
Perl one-liner approach, suitable as probably every shell have perl preinstalled:
Using
sed
- tool suited for tasks as batch or stream editing of text files or streams.as a filter to be used in a pipe:
sed 's/^[0-9]$/0&/'
as a command to edit a file:
sed -i 's/^[0-9]$/0&/' numfile.txt
The code will prepend
0
to lines containing just a single digit0
-9
. Instead of[0-9]
you can also use[[:digit:]]
.You can use
printf
to pad the numbers with0
accordingly:To save the output in the same file:
awk
approach. Redirecting output back to file with creatingtmp.txt
and replacing original file withtmp.txt
once the command is done.Command
Sample output