I'm an awk newbie, so please bear with me.
The goal is to change the case of a string such that the first letter of every word is uppercase and the remaining letters are lowercase. (To keep the example simple, "word" is defined here as strictly alphabetic characters; all others are considered separators.)
I learned a nice way to make the first letter of every word uppercase from another post on this website using the following awk command:
echo 'abce efgh ijkl mnop' | awk '{for (i=1;i <= NF;i++) {sub(".",substr(toupper($i),1,1),$i)} print}'
--> Abcd Efgh Ijkl Mnop
Making the remaining letters lowercase is easily accomplished by preceding the awk command with a tr command:
echo 'aBcD EfGh ijkl MNOP' | tr [A-Z] [a-z] | awk '{for (i=1;i <= NF;i++) {sub(".",substr(toupper($i),1,1),$i)} print}'
--> Abcd Efgh Ijkl Mnop
However, in the interest of learning more about awk, I wanted to change the case of all but the first letter to lowercase with a similar awk construct. I used the regular expression \B[A-Za-z]+
to match all letters of a word but the first, and the awk command substr(tolower($i),2)
to provide those same letters in lowercase, as follows:
echo 'ABCD EFGH IJKL MNOP' | awk '{for (i=1;i <= NF;i++) {sub("\B[A-Za-z]+",substr(tolower($i),2),$i)} print}'
--> Abcd EFGH IJKL MNOP
Notice that the first word converted properly, but the remaining words are left unchanged. I would be very grateful for an explanation of why the remaining words did not convert properly and how to get them to do so.