Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed command - Naming captured group

Back references (e.g. "\3") are not very practical when you are writing a substitution command using sed with many captured groups (e.g. to convert an access log line to another format).

Beside, if you add another capture group at the beginning, you have to update the substitution pattern too, i.e. adding +1 to all back references.

So, is there a way to name captured group in sed command instead of using back-references?

like image 952
Sylmarch Avatar asked May 16 '26 20:05

Sylmarch


1 Answers

sed does not support named backreferences.

Perl supports them, and you may specify any amount of named capturing groups with the same name in the pattern:

perl -pe 's/(?<i>b)ash|(?<i>sl)ash|(?<i>m)ash/$+{i}ong/g' <<< "bash slash mash"

Result:

bong slong mong

See demo

like image 84
Ryszard Czech Avatar answered May 19 '26 09:05

Ryszard Czech



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!