Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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.

like image 938
Ubuntourist Avatar asked Jan 31 '26 00:01

Ubuntourist


1 Answers

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
like image 74
Wiktor Stribiżew Avatar answered Feb 01 '26 15:02

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!