Hi all,
I am trying to find a way to change first letter in a word from lower case to upper case. It should be done for each first word in text or in paragraph, and also for each word after punctuation like
. ; : ! ?
I found the following command
sed -i 's/[\.;:!?]\s*./\U&\E/g' $@ filename
but unfortunately it does not work.
Your help is greatly appreciated.
Try
Sed
for each word
$ echo foo test | sed 's/\([a-z]\)\([a-zA-Z0-9]*\)/\u\1\2/g'
Foo Test
Awk
$ echo foo test | awk '{$1=toupper(substr($1,0,1))substr($1,2)}1'
Foo test
1 Like
Yoda
October 20, 2013, 10:00am
3
An approach using awk:
awk '
{
for ( i = 1; i <= NF; i++ )
{
if ( i == 1 )
$i = sprintf ( "%s", toupper ( substr ( $i, 1, 1 ) ) substr ( $i, 2 ) )
if ( $i ~ /[.;:!?]/ )
$(i+1) = sprintf ( "%s", toupper ( substr ( $(i+1), 1, 1 ) ) substr ( $(i+1), 2 ) )
}
print
}
' file
2 Likes
Try
Sed
for each word
$ echo foo test | sed 's/\([a-z]\)\([a-zA-Z0-9]*\)/\u\1\2/g'
Foo Test
Awk
$ echo foo test | awk '{$1=toupper(substr($1,0,1))substr($1,2)}1'
Foo test
the first command changes every word in the text
second command change every first word in the paragraph but not after the specified punctuation
Yeah for that you need to refer Yoda's solution
yoda:
An approach using awk:
awk '
{
for ( i = 1; i <= NF; i++ )
{
if ( i == 1 )
$i = sprintf ( "%s", toupper ( substr ( $i, 1, 1 ) ) substr ( $i, 2 ) )
if ( $i ~ /[.;:!?]/ )
$(i+1) = sprintf ( "%s", toupper ( substr ( $(i+1), 1, 1 ) ) substr ( $(i+1), 2 ) )
}
print
}
' file
your code works great.
thank you very much
sea
October 20, 2013, 11:32am
7
i'm using this function to change the first letter of a word to caps:
Capitalize() { # STRING
# Makes first char capital
# by stevea & shorten by dd_wizard @ fedoraforum.org
low=${1,,}
echo ${low^}
}
Call it like:
echo $(Capitalize abc)
Hope this helps for re-usage, imho easier, though doesnt do parsings.
1 Like
RudiC
October 20, 2013, 12:32pm
8
Alternative, taking into account not just new lines but paragraphs (if a paragraph separator is defined as an empty line) and also considering punctuation only at the end of words:
awk '!NF || NR==1 {P=1}
{for (i=1; i<=NF; i++) {if (P) $i=toupper(substr($i,1,1)) substr($i,2)
P = $i ~ /[.;:!?]$/
}
}
1
' file
1 Like