How to remove extra spaces from filenames using power shell?

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

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

in a power shell. I believe it has something to do with not being explicit that the "()" symbols were not part of any expression, and I was not aware of it. I have a whole bunch of files with example names

H ow T o C raft () [.zip

or

V i deo G ame () [.zip

This is the space between each letter and two spaces between each word Now I need to convert to

How to make Craft.zip

Video Game.zip

and I am pretty new to using regex and power shell in general. If anyone can help me use the command to remove double spacing between words, single letter spacing and any instance of a character (and all text after a (this will solve all my problems.

+3


source to share


2 answers


You can use the \s

regex whitespace character class to replace whitespace, Trim()

to remove special characters at the end, and put 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"
}

      

+1


source


You can recover filenames with the following regex replacement:

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

      

or

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

      



And replacement: $1

.

See demo 1 or demo 2 .

So now it will look like

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

      

0


source







All Articles