Home > Net >  Capitalize first letter of each line
Capitalize first letter of each line

Time:09-17

I have a list like below:

david
Sam
toNy
3matt
5$!john

I wish to capitalize the first occurrence of a letter in each line. So if the line does not begin with a letter then go to the next possible letter and make the into capital. So the above example should output:

David
Sam
ToNy
3Matt
5$!John

I have tried the following but it does not capitalize the first occurrence of a letter if the line begins with a number or symbol:

sed  's/^\(.\)/\U\1/' myfile.txt > convertedfile.txt

I have searched this site for answers already and they all give the same problem as the line above

CodePudding user response:

You can use

sed 's/[[:alpha:]]/\U&/' myfile.txt > convertedfile.txt

Here, s/[[:alpha:]]/\U&/ finds the first letter (with [[:alpha:]]) and it is capitalized with \U operator (& stands for the whole match, the matched letter). As there is no /g flag, only the first occurrence (per line) is affected.

See the online demo:

s='david
Sam
toNy
3matt
5$!john'
sed 's/[[:alpha:]]/\U&/' <<< "$s"

Output:

David
Sam
ToNy
3Matt
5$!John
  • Related