Reputation: 1461
I'm trying to capitalize the first letter of every word in a string using the following sed command, but it's not working:
echo "my string" | sed 's/\b\(.\)/\u\1/g'
Output:
my string
What am I doing wrong?
Thank you
Upvotes: 4
Views: 6619
Reputation: 720
Here is a sed solution that works on OSX:
echo 'my string
ANOTHER STRING
tHiRd StRiNg' | sed -En '
y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/
:loop
h
s/^(.*[^a-zA-Z0-9])?([a-z]).*$/\2/
t next
b end
:next
y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/
G
s/^(.+)\n(.*[^a-zA-Z0-9])?[a-z](.*)$/\2\1\3/
t loop
:end
p
'
Output:
My String
Another String
Third String
The sed command works as follows:
Here is how the loop works:
Execution speed testing revealed that the current sed approach executes at approximately the same speed as the awk solution submitted by Ed Morton.
Upvotes: 1
Reputation: 203684
Given your sample input, this will work in any awk:
$ echo 'my string' | awk '{for (i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) substr($i,2)} 1'
My String
If that doesn't do what you really want then edit your question to show some more truly representative sample input and expected output.
Upvotes: 10
Reputation: 415
This has already been addressed: Uppercasing First Letter of Words Using SED
I get the correct behavior with GNU sed, but not with the standard BSD sed that ships with OS X. I think the \u "regular expression" is a GNU thing. How about "port install gsed"?
Edit: if you really want to use BSD sed, which I would not recommend (because the command becomes very ugly), then you can do the following:
sed -E "s:([^[:alnum:]_]|^)a:\1A:g; s:([^[:alnum:]_]|^)b:\1B:g; s:([^[:alnum:]_]|^)c:\1C:g; s:([^[:alnum:]_]|^)d:\1D:g; s:([^[:alnum:]_]|^)e:\1E:g; s:([^[:alnum:]_]|^)f:\1F:g; s:([^[:alnum:]_]|^)g:\1G:g; s:([^[:alnum:]_]|^)h:\1H:g; s:([^[:alnum:]_]|^)i:\1I:g; s:([^[:alnum:]_]|^)j:\1J:g; s:([^[:alnum:]_]|^)k:\1K:g; s:([^[:alnum:]_]|^)l:\1L:g; s:([^[:alnum:]_]|^)m:\1M:g; s:([^[:alnum:]_]|^)n:\1N:g; s:([^[:alnum:]_]|^)o:\1O:g; s:([^[:alnum:]_]|^)p:\1P:g; s:([^[:alnum:]_]|^)q:\1Q:g; s:([^[:alnum:]_]|^)r:\1R:g; s:([^[:alnum:]_]|^)s:\1S:g; s:([^[:alnum:]_]|^)t:\1T:g; s:([^[:alnum:]_]|^)u:\1U:g; s:([^[:alnum:]_]|^)v:\1V:g; s:([^[:alnum:]_]|^)w:\1W:g; s:([^[:alnum:]_]|^)x:\1X:g; s:([^[:alnum:]_]|^)y:\1Y:g; s:([^[:alnum:]_]|^)z:\1Z:g;"
Upvotes: -1