1

I am trying to take some text that is all lowercase i.e. firstname.lastname and using awk, make it capital First.Last. The problem I'm seeing is the period needs to come through as a literal character, and the last name needs to be capitalized.

I have tried using sed, but was unsuccessful as it is in a macOS script.

I looked here Changing the case of a string with awk

but was unable to have any success

echo 'first.last' | awk '{print toupper(substr($0,1,1)) tolower(substr($0,2)) }'

This code was the closest I got, but the result came out as First.last

I would like to see the output as First.Last

Inian
  • 80,270
  • 14
  • 142
  • 161
barrett316
  • 11
  • 2
  • `sed` should work fine on MacOS too, though you probably have to adjust the script slightly compared to e.g. Linux if you don't use only the strict well-defined POSIX subset of the capabilities. – tripleee Aug 28 '19 at 05:16
  • 1
    as far as I know, only GNU sed supports case changing, for ex: `echo 'first.last' | sed -E 's/\w+/\u&/g'` ... perl is a good option in such cases, `echo 'first.last' | perl -pe 's/\w+/\u$&/g'`.. if your input isn't always all lowercase, use `echo 'fiRsT.laSt' | perl -pe 's/\w+/\L\u$&/g'` – Sundeep Aug 28 '19 at 05:25

1 Answers1

3

You can do

echo 'first.last' | awk -F. '{print toupper(substr($1,1,1)) substr($1,2) FS toupper(substr($2,1,1)) substr($2,2)}'
First.Last

A more generic solution

echo 'first.last' | awk -F. -v OFS=. '{for(i=1;i<=NF;++i) $i=toupper(substr($i,1,1)) tolower(substr($i,2))}1'
First.Last

Some extra gnu sed

echo 'first.last' | sed 's/\b\(.\)/\u\1/g'
First.Last


echo 'first.last' | sed 's/\b./\u&/g'
echo 'first.last' | sed 's/\b./\u\0/g'
First.Last


echo 'first.last' | sed 's/\<./\u&/g'
First.Last
Jotne
  • 40,548
  • 12
  • 51
  • 55