简体   繁体   中英

Snake case to lower camel case with regex and sed

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' {} + find. -name "*.swift" -exec gsed -r -i 's/_(.)/\U\1/gi' {} + cmd to search and replace

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' {} +

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM