Mark Pelletier
Mark Pelletier

Reputation: 1359

Replace Single Quotes (') in Filenames

I received a good suggestion in another thread to support the removal/replacement of specific characters from filenames in a directory structure. Works as expected for common ascii characters (like &).

PowerShell (works fine to remove & character from filenames):

powershell.exe -c "Get-ChildItem 'c:\Media\Downloads' -Filter '*&*' -Recurse | Rename-Item -NewName {$_.name -replace '&','' }"

I also need remove single quotes from some files: Example: mark's_file.txt.

I've tried a few variants without success. I think I am running into a punctuation issue I am unable sort out. I also tried using a variable = char(39) and adding to the string. No luck.

Any ideas to accomplish?

Note: Would like a self contained batch file approach, vs calling an external .ps1 file.

Upvotes: 1

Views: 4058

Answers (1)

Aacini
Aacini

Reputation: 67216

A Batch file also works fine to remove both & and ' characters from filenames:

@echo off
setlocal EnableDelayedExpansion

rem Remove "&" characters:
for /R "c:\Media\Downloads" %%a in ("*&*") do (
   set "fileName=%%~NXa"
   ren "%%a" "!filename:&=!"
)

rem Remove "'" characters:
for /R "c:\Media\Downloads" %%a in ("*'*") do (
   set "fileName=%%~NXa"
   ren "%%a" "!filename:'=!"
)

... but the Batch file start run much faster than the PS one!

Upvotes: 4

Related Questions