user8727588
user8727588

Reputation:

Pad one-digit, two-digit and three-digit numbers with zeros with sed

I'm programming a bash script that pads one-digit, two-digit and three-digit numbers with zeros. For example:

file.txt:

2
22
222
2222
a2a2
2a2a
a22a
2aa2
22a2

output.txt:

0002
0022
0222
2222
a0002a0002
0002a0002a
a00022a
0002aa0002
0022a0002

The purpose of this script is to fill the digits until they reach a maximum of 4 digits.

I have to do it with the sed command. I thought about doing it like this, but it doesn't work like I want.

sed -r -i 's/[0-9]{1}/0&/g' file.txt

Upvotes: 1

Views: 698

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

GNU awk solution:

awk -v FPAT='[0-9]+|[^0-9]+' '{ 
           for (i=1;i<=NF;i++) printf ($i~/[0-9]/? "%04d":"%s"),$i; 
           print "" 
       }' file.txt

The output:

0002
0022
0222
2222
a0002a0002
0002a0002a
a0022a
0002aa0002
0022a0002

Upvotes: 3

Benjamin W.
Benjamin W.

Reputation: 52132

$ sed -E 's/([[:digit:]]+)/000&/g;s/0+([[:digit:]]{4})/\1/g' file.txt
0002
0022
0222
2222
a0002a0002
0002a0002a
a0022a
0002aa0002
0022a0002

The first substitution prepends 000 to every group of digits in the line. The second substitution removes zeroes from the beginning of every group of digits until there are only four digits left.

The intermediate output after the first substitution is thus

$ sed -E 's/([[:digit:]]+)/000&/g' file.txt
0002
00022
000222
0002222
a0002a0002
0002a0002a
a00022a
0002aa0002
00022a0002

and the second substitution removes the extra zeroes.

Upvotes: 4

Related Questions