Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalize the first letter of each word in a filename with powershell

I want to change the names of some files automatically.

With this code I change the lowercase letters to uppercase:

get-childitem *.mp3 | foreach { if ($.Name -cne $.Name.ToUpper()) { ren $.FullName $.Name.ToUpper() } }

But I only want the first letter of each word to be uppercase.

like image 922
Gilko Avatar asked Mar 27 '14 17:03

Gilko


4 Answers

You can use ToTitleCase Method:

$TextInfo = (Get-Culture).TextInfo
$TextInfo.ToTitleCase("one two three")

outputs

One Two Three

$TextInfo = (Get-Culture).TextInfo
get-childitem *.mp3 | foreach { $NewName = $TextInfo.ToTitleCase($_); ren $_.FullName $NewName }
like image 173
Klark Avatar answered Nov 18 '22 13:11

Klark


Yup, it's built into Get-Culture.

gci *.mp3|%{
    $NewName = (Get-Culture).TextInfo.ToTitleCase($_.Name)
    $NewFullName = join-path $_.directory -child $NewName
    $_.MoveTo($NewFullName)
}

Yeah, it could be shortened to one line, but it gets really long and is harder to read.

like image 37
TheMadTechnician Avatar answered Nov 18 '22 12:11

TheMadTechnician


My answer is very similar, but I wanted to provide a one-line solution. This also forces the text to lowercase before forcing title case. (otherwise, only the first letter is effected)

$text = 'one TWO thrEE'
( Get-Culture ).TextInfo.ToTitleCase( $text.ToLower() )

Output:

One Two Three

like image 4
Rob Traynere Avatar answered Nov 18 '22 13:11

Rob Traynere


There you go

[cultureinfo]::GetCultureInfo("en-US").TextInfo.ToTitleCase("what is my name?")
like image 2
Fatman Avatar answered Nov 18 '22 11:11

Fatman