I need a script in any language to capitalize the first letter of every word in a file.
我需要一个任何语言的脚本来大写文件中每个单词的第一个字母。
Thanks for all the answers.
感谢所有的答案。
* rocks!
20 个解决方案
#1
In Python, open('file.txt').read().title()
should suffice.
在Python中,打开('file.txt')。read()。title()就足够了。
#2
Using the non-standard (Gnu extension) sed
utility from the command line:
使用命令行中的非标准(Gnu扩展)sed实用程序:
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.
如果您不希望它就地修改文件,请删除“-i”。
note that you should not use this in portable scripts
请注意,您不应在便携式脚本中使用它
#3
C#:
string foo = "bar baz";
foo = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(foo);
//foo = Bar Baz
#4
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:
在shell中,使用ruby,这可以假设您的输入文件名为FILENAME,它应该保留所有现有的文件格式 - 它不会像其他一些解决方案那样折叠间距:
cat FILENAME | ruby -n -e 'puts $_.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase }'
#5
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(" "))
#6
You can do it with Ruby
too, using the command line format in a terminal:
您也可以使用Ruby在终端中使用命令行格式:
cat FILENAME | ruby -n -e 'puts gsub(/\b\w/, &:upcase)'
Or:
ruby -e 'puts File.read("FILENAME").gsub(/\b\w/, &:upcase)'
#7
A simple perl script that does this: (via http://www.go4expert.com/forums/showthread.php?t=2138)
这是一个简单的perl脚本:(通过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
#8
bash:
$ X=(hello world)
$ echo ${X[@]^}
Hello World
#9
This is done in PHP.
这是在PHP中完成的。
$string = "I need a script in any language to capitalize the first letter of every word in a file."
$cap = ucwords($string);
#10
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()
#11
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使用ucwords($ string)或ucwords('所有这些将以大写字母'开头)来完成这个伎俩。所以你可以打开一个文件并获取数据,然后使用这个函数:
<?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.
编辑,我的代码被切断了。抱歉。
#12
Here's another Ruby solution, using Ruby's nice little one-line scripting helpers (automatic reading of input files etc.)
这是另一个Ruby解决方案,使用Ruby的漂亮的小型单行脚本助手(自动读取输入文件等)
ruby -ni~ -e "puts $_.gsub(/\b\w+\b/) { |word| word.capitalize }" foo.txt
(Assuming your text is stored in a file named foo.txt
.)
(假设您的文本存储在名为foo.txt的文件中。)
Best used with Ruby 1.9 and its awesome multi-language support if your text contains non-ASCII characters.
如果您的文本包含非ASCII字符,最好与Ruby 1.9一起使用,以及其出色的多语言支持。
#13
ruby:
irb> foo = ""; "foo bar".split.each { |x| foo += x.capitalize + " " }
=> ["foo", "bar"]
irb> foo
=> "Foo Bar "
#14
In ruby:
str.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase }
hrm, actually this is nicer:
hrm,实际上这更好:
str.each(' ') {|word| puts word.capitalize}
#15
perl:
$ perl -e '$foo = "foo bar"; $foo =~ s/\b(\w)/uc($1)/ge; print $foo;'
Foo Bar
#16
Although it was mentioned in the comments, nobody ever posted the awk
approach to this problem:
虽然在评论中提到过,但没有人发布awk方法来解决这个问题:
$ 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.
Explanation
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.
我们遍历字段并将每个单词的首字母大写。如果字段分隔符不是空格,我们可以使用-F“\ t”,-F“_”或其他任何内容来定义它。
#17
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
.
注意它在每个非alpha字符后都有CAP,请参阅VB.Net。
#18
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.
Amiga上AMOS Basic的基本版本 - 仅将空格视为单词分隔符。我确信有更好的方式使用PEEK和POKE,但是我的记忆相当生疏,超过15年。
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.
我想念一个很好的旧AMOS,一个很好学习的语言......虽然很难看,呵呵。
#19
Another solution with awk, pretending to be simpler instead of being shorter ;)
使用awk的另一种解决方案,假装更简单而不是更短;)
$ 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
#20
If using pipes and Python:
如果使用管道和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()
:
您还可以使用strip()之类的东西来移除空格,或者使用大写():
$ echo " This iS mY USER ${USER} " | python3 -c "import sys; print(sys.stdin.read().strip().lower().capitalize())"
This is my user jenkins
#1
In Python, open('file.txt').read().title()
should suffice.
在Python中,打开('file.txt')。read()。title()就足够了。
#2
Using the non-standard (Gnu extension) sed
utility from the command line:
使用命令行中的非标准(Gnu扩展)sed实用程序:
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.
如果您不希望它就地修改文件,请删除“-i”。
note that you should not use this in portable scripts
请注意,您不应在便携式脚本中使用它
#3
C#:
string foo = "bar baz";
foo = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(foo);
//foo = Bar Baz
#4
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:
在shell中,使用ruby,这可以假设您的输入文件名为FILENAME,它应该保留所有现有的文件格式 - 它不会像其他一些解决方案那样折叠间距:
cat FILENAME | ruby -n -e 'puts $_.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase }'
#5
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(" "))
#6
You can do it with Ruby
too, using the command line format in a terminal:
您也可以使用Ruby在终端中使用命令行格式:
cat FILENAME | ruby -n -e 'puts gsub(/\b\w/, &:upcase)'
Or:
ruby -e 'puts File.read("FILENAME").gsub(/\b\w/, &:upcase)'
#7
A simple perl script that does this: (via http://www.go4expert.com/forums/showthread.php?t=2138)
这是一个简单的perl脚本:(通过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
#8
bash:
$ X=(hello world)
$ echo ${X[@]^}
Hello World
#9
This is done in PHP.
这是在PHP中完成的。
$string = "I need a script in any language to capitalize the first letter of every word in a file."
$cap = ucwords($string);
#10
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()
#11
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使用ucwords($ string)或ucwords('所有这些将以大写字母'开头)来完成这个伎俩。所以你可以打开一个文件并获取数据,然后使用这个函数:
<?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.
编辑,我的代码被切断了。抱歉。
#12
Here's another Ruby solution, using Ruby's nice little one-line scripting helpers (automatic reading of input files etc.)
这是另一个Ruby解决方案,使用Ruby的漂亮的小型单行脚本助手(自动读取输入文件等)
ruby -ni~ -e "puts $_.gsub(/\b\w+\b/) { |word| word.capitalize }" foo.txt
(Assuming your text is stored in a file named foo.txt
.)
(假设您的文本存储在名为foo.txt的文件中。)
Best used with Ruby 1.9 and its awesome multi-language support if your text contains non-ASCII characters.
如果您的文本包含非ASCII字符,最好与Ruby 1.9一起使用,以及其出色的多语言支持。
#13
ruby:
irb> foo = ""; "foo bar".split.each { |x| foo += x.capitalize + " " }
=> ["foo", "bar"]
irb> foo
=> "Foo Bar "
#14
In ruby:
str.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase }
hrm, actually this is nicer:
hrm,实际上这更好:
str.each(' ') {|word| puts word.capitalize}
#15
perl:
$ perl -e '$foo = "foo bar"; $foo =~ s/\b(\w)/uc($1)/ge; print $foo;'
Foo Bar
#16
Although it was mentioned in the comments, nobody ever posted the awk
approach to this problem:
虽然在评论中提到过,但没有人发布awk方法来解决这个问题:
$ 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.
Explanation
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.
我们遍历字段并将每个单词的首字母大写。如果字段分隔符不是空格,我们可以使用-F“\ t”,-F“_”或其他任何内容来定义它。
#17
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
.
注意它在每个非alpha字符后都有CAP,请参阅VB.Net。
#18
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.
Amiga上AMOS Basic的基本版本 - 仅将空格视为单词分隔符。我确信有更好的方式使用PEEK和POKE,但是我的记忆相当生疏,超过15年。
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.
我想念一个很好的旧AMOS,一个很好学习的语言......虽然很难看,呵呵。
#19
Another solution with awk, pretending to be simpler instead of being shorter ;)
使用awk的另一种解决方案,假装更简单而不是更短;)
$ 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
#20
If using pipes and Python:
如果使用管道和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()
:
您还可以使用strip()之类的东西来移除空格,或者使用大写():
$ echo " This iS mY USER ${USER} " | python3 -c "import sys; print(sys.stdin.read().strip().lower().capitalize())"
This is my user jenkins