Tutorial :How can I capitalize the first letter of each word?


I need a script in any language to capitalize the first letter of every word in a file.

Thanks for all the answers.

Stackoverflow rocks!


In Python, open('file.txt').read().title() should suffice.


Using the non-standard (Gnu extension) sed utility from the command line:

sed -i '' -r 's/\b(.)/\U\1/g' file.txt  

Get rid of the "-i" if you don't want it to modify the file in-place.

note that you should not use this in portable scripts



string foo = "bar baz";  foo = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(foo);  //foo = Bar Baz  


From the shell, using ruby, this works assuming your input file is called FILENAME, and it should preserve all existing file formatting - it doesn't collapse the spacing as some other solutions might:

cat FILENAME | ruby -n -e 'puts $_.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase }'  



scala> "hello world" split(" ") map(_.capitalize) mkString(" ")  res0: String = Hello World  

or well, given that the input should be a file:

import scala.io.Source  Source.fromFile("filename").getLines.map(_ split(" ") map(_.capitalize) mkString(" "))  


You can do it with Ruby too, using the command line format in a terminal:

cat FILENAME | ruby -n -e 'puts gsub(/\b\w/, &:upcase)'  


ruby -e 'puts File.read("FILENAME").gsub(/\b\w/, &:upcase)'  


A simple perl script that does this: (via http://www.go4expert.com/forums/showthread.php?t=2138)

sub ucwords {    $str = shift;    $str = lc($str);    $str =~ s/\b(\w)/\u$1/g;    return $str;  }    while (<STDIN>) {      print ucwords $_;  }  

Then you call it with

perl ucfile.pl < srcfile.txt > outfile.txt  



$ X=(hello world)  $ echo ${X[@]^}  Hello World  


This is done in PHP.

$string = "I need a script in any language to capitalize the first letter of every word in a file."  $cap = ucwords($string);  


VB.Net:    Dim sr As System.IO.StreamReader = New System.IO.StreamReader("c:\lowercase.txt")  Dim str As String = sr.ReadToEnd()  sr.Close()  str = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str)  Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter("c:\TitleCase.txt")  sw.Write(str)  sw.Close()  


php uses ucwords($string) or ucwords('all of this will start with capitals') to do the trick. so you can just open up a file and get the data and then use this function:

<?php   $file = "test.txt";   $data = fopen($file, 'r');  $allData = fread($data, filesize($file));  fclose($fh);  echo ucwords($allData);  ?>  

Edit, my code got cut off. Sorry.


Here's another Ruby solution, using Ruby's nice little one-line scripting helpers (automatic reading of input files etc.)

ruby -ni~ -e "puts $_.gsub(/\b\w+\b/) { |word| word.capitalize }" foo.txt  

(Assuming your text is stored in a file named foo.txt.)

Best used with Ruby 1.9 and its awesome multi-language support if your text contains non-ASCII characters.



irb> foo = ""; "foo bar".split.each { |x| foo += x.capitalize + " " }  => ["foo", "bar"]    irb> foo  => "Foo Bar "  


In ruby:

str.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase }  

hrm, actually this is nicer:

str.each(' ') {|word| puts word.capitalize}  



$ perl -e '$foo = "foo bar"; $foo =~ s/\b(\w)/uc($1)/ge; print $foo;'  

Foo Bar


Although it was mentioned in the comments, nobody ever posted the awk approach to this problem:

$ cat output.txt  this is my first sentence. and this is the second sentence. that one is the third.  $  $ awk '{for (i=0;i<=NF;i++) {sub(".", substr(toupper($i), 1,1) , $i)}} {print}' output.txt   This Is My First Sentence. And This Is The Second Sentence. That One Is The Third.  


We loop through fields and capitalize the first letter of each word. If field separator was not a space, we could define it with -F "\t", -F "_" or whatever.


zsh solution

#!/bin/zsh  mystring="vb.net lOOKS very unsexy"  echo "${(C)mystring}"  Vb.Net Looks Very Unsexy  

Note it does CAP after every non alpha character, see VB.Net .


Very basic version for AMOS Basic on the Amiga â€" only treats spaces as word separators though. I'm sure there is a better way using PEEK and POKE, but my memory is rather rusty with anything beyond 15 years.

FILE$=Fsel$("*.txt")  Open In 1,FILE$  Input #1,STR$  STR$=Lower$(STR$)  L=Len($STR)  LAST$=" "  NEW$=""  For I=0 to L-1    CUR$=MID$(STR$,I,1)    If LAST$=" "      NEW$=NEW$+Upper$(CUR$)    Else      NEW$=NEW$+$CUR$    Endif    LAST$=$CUR$  Next  Close 1  Print NEW$  

I miss good old AMOS, a great language to learn with... pretty ugly though, heh.


Another solution with awk, pretending to be simpler instead of being shorter ;)

$ cat > file    thanks for all the fish    ^D  $ awk 'function tocapital(str) {             if(length(str) > 1)                 return toupper(substr(str, 1, 1)) substr(str,2)             else                 return toupper(str)         }           {             for (i=1;i<=NF;i++)                  printf("%s%s", tocapital($i), OFS);             printf ORS         }        ' < file    Thanks For All The Fish  


If using pipes and Python:

$ echo "HELLO WORLD" | python3 -c "import sys; print(sys.stdin.read().title())"  Hello World  

For example:

$ lorem | python3 -c "import sys; print(sys.stdin.read().title())"  Officia Est Omnis Quia. Nihil Et Voluptatem Dolor Blanditiis Sit Harum. Dolore Minima Suscipit Quaerat. Soluta Autem Explicabo Saepe. Recusandae Molestias Et Et Est Impedit Consequuntur. Voluptatum Architecto Enim Nostrum Ut Corrupti Nobis.  

You can also use things like strip() to remove spaces, or capitalize():

$ echo "  This iS mY USER ${USER}   " | python3 -c "import sys; print(sys.stdin.read().strip().lower().capitalize())"  This is my user jenkins  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »