Reputation: 41
I would like to replace with one sed command first n letter to uppercase.
Example 'madrid' to 'MADrid'. (n=3)
I know how to change first letter to uppercase with this command:
sed -e "s/\b\(.\)/\U\1/g"
but I dont know how to change this command for my problem.
I tried to change
sed -e "s/\b\(.\)/\U\1/g"
to
sed -e "s/\b\(.\)/\U\3/g"
but this didnt work. Also, I googled and searched on this site but exact answer with my problem I couldnt find.
Thank you.
Upvotes: 4
Views: 212
Reputation: 58440
This might work for you (GNU sed):
sed -r 's/[a-z]/&\n/'"$n"';s/^([^\n]*)\n/\U\1/' file
Where $n
is the first n letters. Putting the question of word boundaries aside this converts n
letters of a-z
consecutive or non-consecutive to upper case i.e. A-Z
N.B. this is two sed commands not one!
Upvotes: 0
Reputation: 438273
I infer from your use of \U
that you're using GNU sed
:
n=3
echo 'madrid' | sed -r 's/\<(.{'"$n"'})/\U\1/g' # -> 'MADrid'
-e
option-r
to enable support for extended regular expressions, which have more familiar syntax and also offer more features.I'm using a single-quoted sed
script with a shell-variable value spliced in so as to avoid confusion between what the shell expands up front and what is interpreted by sed
itself.
\<
is used instead of \b
, because unlike the latter it only matches at the start of a word.Thanks, Casimir et Hippolyte
The above replaces any 3 characters at the start of a word, however.
To limit it to at most $n
letters:
sed -r 's/\<([[:alpha:]]{1,'"$n"'})/\U\1/g'
As for what you've tried:
The \3
in your attempt sed -e "s/\b\(.\)/\U\3/g"
refers to the 3rd capture group (parenthesized subexpression, (...)
) in the regex (which doesn't exist), it does not refer to 3 repetitions.
Instead, you have to make sure that your one and only capture group (which you can reference as \1
in the substitution) itself captures as many characters as desired - which is what the {<n>}
quantifier is for; the related {<m>,<n>}
construct matches a range of repetitions.
Upvotes: 4