how to delete one or more spaces at the end of a filename using windows powershell regex? -


i have directory containing lot of files missformated filenames. of them have "spaces" right @ end of filename. others have keywords meshed within filename @ end of filename string. example "xxx xxx xxx somewordeng .txt"

im trying rid of them using script, wont yet. spaces @ end of filename (basename) still there , "eng" keyword somehow added word before:

dir | rename-item -newname { $_.basename.replace("eng$","").replace(" {2,}"," ").replace("\s$","") + $_.extension }  .replace("eng$","")  supposed remove "eng" keyword if appears @ end of filename (basename), seems not working far.  .replace(" {2,}"," ")   supposed replace 2 or more following spaces 1 space within filename, seems not working far.  .replace("\s$","")    supposed remove spaces @ end of filename, not work neither.  

i searched powershell regex examples, seems nothing worked far me. :( cant see problem yet.

the issue have here string method .replace() not support regular expressions trying here. should using replace operator -replace instead. differences between 2 options covered little more in this answer

the following 2 examples show differnce

ps c:\users\mcameron> "te.t".replace(".","s") test  ps c:\users\mcameron> "te.t" -replace ".","s" ssss  

in case

$_.basename -replace "eng$" -replace " {2,}"," " -replace "\s$" 

we use correct operator , can still "chain" them see above. remove trailing word "eng" , trailing single whitespace. reduce group of whitespace single space. if replacing nothing can omit second parameter.

however can tighten little if wanted.

$_.basename -replace "(eng|\s+)$" -replace "\s{2,}"," " 

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -