0

I have a couple .pdf files with with the following:

filename_garbage.pdf

I would like to rename the files by removing the _garbage in one fell swoop to

filename.pdf

The file name is unique as is the _garbage which is also a variable length.

Ie:

123456_1.pdf
789012_1000.pdf
345678_garbage.pdf

rename to :

123456.pdf
789012.pdf
345678.pdf

I know it is a multi-step process, but so far not having any success.

Ken White
  • 123,280
  • 14
  • 225
  • 444
shykitten
  • 35
  • 6
  • 1
    Possible duplicate of [Rename all files in a directory with a Windows batch script](http://stackoverflow.com/questions/9383032/rename-all-files-in-a-directory-with-a-windows-batch-script) – Ken White Apr 06 '16 at 21:54

2 Answers2

1
for /f "tokens=1*delims=_" %%a in ('dir /b "*_*.*"') do ren "%%a_%%b" "%%a%%~xb"

Suggest you echo the ren commands for verification purposes before applying the script in anger.

If run directly from the prompt, reduce %%n to %n

Magoo
  • 77,302
  • 8
  • 62
  • 84
0

On Windows Vista or newer? Use PowerShell. It's a one step process in a reasonably modern language.

gci | ren -NewName { $_ -replace '_.*(?=\.)' }

which is short for

Get-ChildItem .\ | Rename-Item -NewName { $_ -replace '_.*(?=\.)' }

and the replace pattern is a regular expression which matches an underscore _ followed by anything, up to a dot ., and it replaces with nothing. So in your examples it replaces _1, _1000, _garbage.

TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87