Xenos
Xenos

Reputation: 39

How can I remove extra whitespace from my file names using power shell?

I was trying to remove everything after a ( in a file name when I accidentally added a lot of whitespace to my file names when I ran this command

Dir | Rename-Item -NewName { $_.Name -replace "()"," "}

in power shell. I suppose it has something to do with not being explicit that the "()" characters were not part of some expression and I didn't realize it. I have a whole bunch of files with example names of

H o w T o C r a f t () [.zip

or

V i d e o G a m e () [.zip

That have a space between each letter and two spaces between each word That I now need to convert into

How To Craft.zip

Video Game.zip

and I am quite a novice on using regex and power shell in general. If someone could help me use a command to remove the double spacing between words, single spacing between letters and any instance of character ( and all text following a ( it would solve all my problems.

Upvotes: 3

Views: 1826

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You can restore the filenames with the following regex replacement:

 (?! )|[()\[\]]+ [()\[\]]+(?=\.)|( )

Or

\s(?!\s)|[()\[\]]+\s+[()\[\]]+(?=\.)|(\s)

And replacement is: $1.

See demo 1 or demo 2.

So, it will now look like

Dir | Rename-Item -NewName { $_.Name -replace "\s(?!\s)|[()\[\]]+\s+[()\[\]]+(?=\.)|(\s)","$1"}

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

You can use the \s regex whitespace character class to replace the spaces, Trim() to remove the special characters at the end and introduce spaces after each word with this brilliant regex pattern:

$Files = Get-ChildItem .\ -Name

$CamelCasePattern = '([A-Z])([A-Z])([a-z])|([a-z])([A-Z])'
$CamelCaseReplace = '$1$4 $2$3$5'

foreach($FileName in $Files){
    # Get the files base name
    $basename = [System.IO.Path]::GetFileNameWithoutExtension($FileName)

    # Remember the extension
    $extension = $FileName.Substring($basename.Length)

    # Remove all whitespace
    $basename = $basename -ireplace '\s',''
    # Remove excess characters at the end
    $basename = $basename.TrimEnd('()[')
    # introduce space after each capitalized word
    $basename = $basename -creplace $CamelCasePattern,$CamelCaseReplace

    # return correct file name
    "$basename$extension"
}

Upvotes: 1

Related Questions