Friday, June 26, 2015

windows - Batch Files to Remove minus sign from Filenames


I am attempting to clean-up some file-names in a particular folder and I'm wondering how I would go about creating a batch file to remove a minus sign from the beginning of each file-name.


I have a bunch of files withthe pattern -FileName.pdf and I'd like to remove the minus sign from the front so I just have FileName.pdf.


So far, I have the following command:


dir /B > Batch.txt
for /f "tokens=1,2" %i in (Batch.txt) DO ren "%i %j" %l

Is there anything simpler I could use?


Thanks in advance


Answer



I'd like to remove the minus sign from the front


Use the following batch file:


@echo off
setlocal enabledelayedexpansion
for /f "tokens=*" %%i in ('dir /b -*.pdf') do (
set _fname=%%i
echo ren %%i !_fname:~1!
)

Notes:



  • This will remove the first character from all filenames matching the expression -*.pdf.

  • Replace echo ren with ren when you are sure the batch file will rename correctly.




Further Reading



  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.

  • dir - Display a list of files and subfolders.

  • enabledelayedexpansion - Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.

  • for /f - Loop command against the results of another command.

  • set - Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.

  • setlocal - Set options to control the visibility of environment variables in a batch file.


No comments:

Post a Comment

linux - How to SSH to ec2 instance in VPC private subnet via NAT server

I have created a VPC in aws with a public subnet and a private subnet. The private subnet does not have direct access to external network. S...