POSIX programming puzzle: Convert snake_case to PascalCase in one line

Raymond Chen posted a PowerShell one-liner to translate from snake_case to PascalCase. I was naturally curious how easy it would be to do in a POSIX environment. It turns out it's pretty easy, and arguably more readable:

echo $t | awk -v RS=_  '{printf("%s%s", toupper(substr($0, 1, 1)), tolower(substr($0, 2)));}'

Here, the -v RS tells awk to split records at _ characters rather than newline. Then, for each record, we print the first character in upper case followed by the rest of the string in lowercase. Since the format string doesn't contain any white space, and the record splitting essentially gobbles up all the underscores, there's nothing left to do at that point.

Copyright © 2019 Jakob Kaivo <jakob@kaivo.net>