user3002428
user3002428

Reputation: 291

Convert first letters of the first 2 words to Upper using sed

I know I can do this with awk, but I want to know how to do it with sed. I know how to convert the first letter of each line to upper:

sed  's/^\(.\)/\U\1/' input > output

But I want to convert the first letters of the first 2 words to Upper.

Input file:

this is my file

Output file:

This Is my file

I think this must be doable with sed, but I can't figure it out.

Upvotes: 0

Views: 95

Answers (4)

glenn jackman
glenn jackman

Reputation: 246877

Just for fun, perl

perl -ane '@F[0,1] = map {ucfirst} @F[0,1]; print "@F"'

Upvotes: 0

fedorqui
fedorqui

Reputation: 289835

You can maybe use -e to do two blocks:

$ echo "this is my file" | sed -e 's/^\(.\)/\U\1/' -e 's/ \(.\)/ \U\1/'
This Is my file                    ^^^^^^^^^^^^^^      ^^^^^^^^^^^^^^^
                                   first word          second word

Note you can make the lines more clear with the -r parameter that allows catching with simple (XXX) instead of \(XXX\):

$ echo "this is my file" | sed -re 's/^(.)/\U\1/' -e 's/ (.)/ \U\1/' 
This Is my file

Upvotes: 1

Jotne
Jotne

Reputation: 41454

I know its not asked for awk, but posting a general solution if other are interested.

echo "this is my file" | awk '{for (i=1;i<=2;i++) sub(".",substr(toupper($i),1,1),$i)}1'
This Is my file

It can easily be change to n number of words, and if you like the two first letter of a word to be changed:

echo "this is my file" | awk '{for (i=1;i<=2;i++) sub("..",substr(toupper($i),1,2),$i)}1'
THis IS my file

Upvotes: 0

devnull
devnull

Reputation: 123558

Use capture groups and \U and \E to turn on-off the uppercase:

sed 's/^\(.\)\([^ ]* \)\(.\)/\U\1\E\2\U\3/' input > output

or

sed -r 's/^(.)([^ ]* )(.)/\U\1\E\2\U\3/' input > output

Quoting from the manual:

\U

Turn the replacement to uppercase until a \L or \E is found

As an example:

$ echo 'this is my life' | sed 's/^\(.\)\([^ ]* \)\(.\)/\U\1\E\2\U\3/'
This Is my life

Upvotes: 0

Related Questions