Looking for a command-line regex search-replace tool with (the key point) a variable number of capture groups, like the Rust declarative macros

I can't use sed to convert camel case to snake case.

I could if I could use a variable number of capture groups.

Rust macros seem to manage it well enough.

Is anyone aware of any command-line regex search-replace tools that similarly allow a variable number of capture groups?

You want the /g flag. Here's a starter:

$ echo 'SomeCamelCaseText' | sed -E 's/([A-Z])([a-z])/_\1\2/g' | tr '[[:upper:]]' '[[:lower:]]'
_some_camel_case_text
1 Like

To clarify, I'm talking about a theoretical syntax like this:

sed -Ei "s/\b([A-Z][a-z]*)([A-Z][a-z]*)*Widget\b/\l\1(_\l\2)*_widget/g" $(find . -type f -name '*')

So running this one-liner in the top directory of my project can rename all of these:

ThingOneWidget --> thing_one_widget
SmallWidget --> small_widget
NearlyAFullSentenceInOneNameWidget --> nearly_a_full_sentence_in_one_name_widget

The brackets and star in the replace side aren't special characters in sed as is, but bringing in the rust macro syntax would let it work fairly analogously.

As it is now, I need to dump all the matches into a tmp text file, modify them line by line (with a smaller scope sed command like suggested above), then use xargs and sed to replace the exact strings. Rust macros make this kind of stuff way less of a pain.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.