-1

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
M9A
  • 3,168
  • 14
  • 51
  • 79
  • 1
    Related: [How to capitalize first letter of each line in bash?](https://stackoverflow.com/q/43705853/2943403), [Using Sed to capitalize the first letter of each word](https://stackoverflow.com/q/25962929/2943403), [Uppercasing First Letter of Words Using SED](https://stackoverflow.com/q/1538676/2943403), [How can I capitalize the first letter of each word?](https://stackoverflow.com/q/880597/2943403) – mickmackusa Sep 10 '21 at 00:25

1 Answers1

8

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
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563