Snake case to lower camel case with regex and sed

Viewed 147

I'm trying to find a proper regex that matches the pattern "some_text".local for sed

("\w*?"\.local) does the job of finding "...".local match, _(.)/\U\1 will find all underscores and replace it with upper case letter next to it. But i don't know how to combine them together so the result would look like this:

self.title = "statistics_title".local
self.title = "title".local

->

self.title = L10n.statisticsTitle
self.title = L10n.title

I use find . -name "*.swift" -exec gsed -r -i 's/_(.)/\U\1/gi' {} + cmd to search and replace

1 Answers

Use a sed loop for that:

sed -r '
    :loop
    s/_([^"]+"\.local)/\u\1/
    t loop

    s/"([^"]+)"\.local/L10n.\1/g
' file.swift

Explanation:

  • The first s only changes one _seq to Seq at a time. Thus, the command is done repeatedly until nothing is matching the pattern _([^"]+"\.local) (.local definition in snake case). t loop means "Go to loop if the last s command was successful.

  • The second s command just turns all "fooBar".local into L10n.fooBar

You can put everyting in one line by using the ; separator:

 find . -name "*.swift" -exec gsed -r -i ':loop; s/_([^"]+"\.local)/\u\1/g; t loop; s/"([^"]+)"\.local/L10n.\1/g' {} +
Related