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!
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!
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.
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);
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
In ruby:
str.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase }
hrm, actually this is nicer:
str.each(' ') {|word| puts word.capitalize}
ruby:
irb> foo = ""; "foo bar".split.each { |x| foo += x.capitalize + " " }
=> ["foo", "bar"]
irb> foo
=> "Foo Bar "
perl:
$ perl -e '$foo = "foo bar"; $foo =~ s/\b(\w)/uc($1)/ge; print $foo;'
Foo Bar
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:
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(" "))
C#:
string foo = "bar baz";
foo = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(foo);
//foo = Bar Baz
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()
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.