bash - dash case to camel case
Asked Answered
B

2

5

I wrote the following to convert something like foo-bar-baz to FooBarBaz

sed -r 's/^(.)|-(.)/\U\1\U\2/g'

(Feel free to correct the above if there is something wrong)

However, it does not work with busybox :(

I could cobble something together with cut, for loops, bash substrings, and tr, but there must be a good one liner using busybox version of sed, awk, whatever. Thoughts?

Borak answered 3/6, 2018 at 16:33 Comment(2)
If busybox doesn't understand \U (which is likely), then a sed solution can't work.Outlawry
You might want to restrict the (.) to have it only match alphabetics, or even only lowercase alphabetics. Perhaps numbers too if that's permissible? ([a-z0-9])Stubbs
H
8

Considering that your actual Input_file(data) is same as shown samples if yes then following awk(s) may help you here.

echo "foo-bar-baz" |
awk -F"-" '{for(i=1;i<=NF;i++){$i=toupper(substr($i,1,1)) substr($i,2)}} 1' OFS=""

Solution 2nd: With use of RS, FS and ORS in awk.

echo "foo-bar-baz" | 
awk 'BEGIN{FS="";RS="-";ORS=""} {$0=toupper(substr($0,1,1)) substr($0,2)} 1'
Hunch answered 3/6, 2018 at 16:41 Comment(3)
Cool. I did not know you could control the IFS and OFS of awk. That lets me get rid of the tr parts in my solution. Thanks!Borak
@Dave, yes we could do much more than that too :) Also try to select an answer a correct answer(after sometime of your post) to close the thread completely, cheers and happy learning.Hunch
If you want classic camel case (=first letter lowercase), change for(i=1 to for(i=2Wordplay
B
-1

I found an awk script that upper cases the first letter of each word. I use tr to convert the dashes to spaces, run the script I stole, then use tr to remove the spaces:

echo "foo-bar-baz" \
    | tr '-' ' ' \
    | awk '{for(i=1;i<=NF;i++){ $i=toupper(substr($i,1,1)) substr($i,2) }}1' \
    | tr -d ' '

Note, this is only the 2nd awk script I wrote, so no guarantees

Still, there must be a better way . . .

Borak answered 3/6, 2018 at 16:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.