Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell replacing periods

Can anyone tell me if they think there is something wrong with this Powershell script.

Dir | 
where {$_.extension -eq ".txt"} | 
Rename-Item –NewName { $_.name –replace “.“,”-” }

For each text file in the current directory, I'm trying to replace all periods in the file names with hyphens. Thanks ahead of time.

like image 612
qmckinsey Avatar asked May 16 '26 01:05

qmckinsey


2 Answers

As the others have said, -replace uses regex (and "." is a special character in regex). However, their solutions are forgetting about the fileextension and they are acutally removing it. ex. "test.txt" becomes "test-txt" (no extension). A better solution would be:

dir -Filter *.txt | Rename-Item -NewName { $_.BaseName.replace(".","-") + $_.Extension }

This also uses -Filter to pick out only files ending with ".txt" which is faster then comparing with where.

like image 125
Frode F. Avatar answered May 18 '26 17:05

Frode F.


-replace operates on regex, you need to escape '.':

rename-item -NewName { $_.Name -replace '\.', '-' }

Otherwise you will end up with '----' name...

like image 40
BartekB Avatar answered May 18 '26 15:05

BartekB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!