Home > Software engineering >  Is there a way to reformat w/ zero-fill a regex match group?
Is there a way to reformat w/ zero-fill a regex match group?

Time:12-04

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.

CodePudding user response:

You can use

perl -i -pe 's/width: (\d )%/sprintf "width_s", $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_s", $1/ge' <<< "$s"

Output:

width_009, width_022, width_100
  •  Tags:  
  • perl
  • Related