1

I'm looking for a script to remove the # character out of any file names in a specific directory (PDF documents).

I've been looking at some similar examples, but it's all a bit confusing!

0

2 Answers 2

3
@echo off &setlocal
cd /d c:\users\data
for /f "delims=" %%a in ('dir /b /a-d *#*.pdf') do (
    set "fname=%%~a"
    setlocal enabledelayedexpansion
    set "nname=!fname:#=!"
    ren "!fname!" "!nname!"
    endlocal
)
9
  • Thats great, thanks very much. Is it possible to get this to point to a specfic directory? i.e c:\users\data?
    – David
    Nov 4, 2013 at 8:39
  • @David look at my edit, pls.
    – Endoro
    Nov 4, 2013 at 23:41
  • Perfect, it works exactly how i need. Thank you very much for the help - very kind of you
    – David
    Nov 5, 2013 at 8:50
  • Any chance to include multiple characters such as ( ) and - as well for /f "delims=" %%a in ('dir /b /a-d *#*') do (
    – Arthor
    Mar 14, 2020 at 19:27
  • 1
    P.S. you may try for /f "delims=" %%a in ('dir /b /a-d *#*.pdf *(*.pdf *)*.pdf') do (, but I'm not sure if it will work if more than one character is to be replaced.
    – Endoro
    Mar 15, 2020 at 0:36
2

It's 2013, you should use PowerShell:

Get-ChildItem | Where-Object {$_.Name -match '#'} | ForEach-Object { Rename-Item -Path $_.Name -NewName $($_.Name -Replace "#", "") -WhatIf }

Navigate to the directory in question and execute the line. It finds all files with a # and then renames each of them. Remove the '-Whatif' to actually perform the operation.

A shorter version using aliases and defaults would be:

ls | ? {$_.Name -match "#"} | ForEach { rni $_.Name $($_.Name -Replace "#", "")}

As least the long version seems more readable to me than the 1980s batch syntax. The only cryptic part here is the '$.Name', '$' in PowerShell refers to the current object in the loop. Here in all cases to the current file. Because we need an expression for the -NewName parameter, we have to wrap it into $()

2
  • Hey, I am thinking of starting with powershell...used batch files for too long now....never bothered to switch to powershell....can you recommend a good place to get started with powershell Nov 1, 2013 at 17:52
  • @tumchaaditya - Not off top of my head. I learned it by using it over the years. But there are tons of books and online resources out there. Nov 1, 2013 at 18:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .