Lots of times I need to convert CSV headers that are lowercase with underscores to camel case. In other words,
I’ll a header like first_name,last_name,date_of_birth
and need to convert it to:
firstName,
lastName,
dateOfBirth
Even better, if I’m generating a Kotlin data class, I’ll generate:
var firstUname: String?,
var lastUname: String?,
var dateUofUbirth: String?
Then, I can just copy/paste into my Kotlin data class:
data class User(
var firstUname: String?,
var lastUname: String?,
var dateUofUbirth: String?,
)
Here is the one-liner to do it:
echo '"first_name","last_name","date_of_birth"' | \
sed 's/"//g' |\
tr , '\n' |\
gsed -E 's/_(.)/\U\1/g' |\
awk '{printf("var %s: String?,\n", $1);}'
Note If you’re on linux you can change the gsed
to just sed
and if you’re on mac you need to do
brew install gnu-sed
Broken down:
"
characters,
with newline_
and replace the following character with the uppercase of itselfvar x: String?,
statement and a newlineYou can adjust the last awk command to generate whatever you like, or remove it to just print one camel case phrase per line…
If you’re serious about Bash scripting - check one of these books out: