Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to reformat w/ zero-fill a regex match group?

Suppose I have a file with " 9%", " 22%", " 100%" and so on.

Is there a Perl (or other) regex way to turn the numbers into "009", "022", and "100" respectively?

perl -p -i -e "s/width: (\d+)%/width_\1/g;" ...

correctly returns "width_9", "width_22", and "width_100", which is okay, but if there’s a clever, yet simple way to take the \1 matched group and add in formatting, it would be nice.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use

perl -i -pe 's/width: (\d+)%/sprintf "width_%03s", $1/ge' file

Here, width: (\d+)% matches width: , then captures one or more digits into Group 1 ($1, not \1!), and a % char is also consumed right after, and the match is replaced with width_ + the reformatted number.

See the online demo:

#!/bin/bash
s='width: 9%, width: 22%, width: 100%'
perl -pe 's/width: (\d+)%/sprintf "width_%03s", $1/ge' <<< "$s"

Output:

width_009, width_022, width_100
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading