0

I have written batch file to extract last 8 character of multiple files in folder. But that batch file not giving desired result. My folder consist of below mentioned filenames sub_rachit_01.pdf and sub_kapoor_02.pdf. I want to extract rachit_01 and kapoor_02 as variable from folder. Batch File is shred below:

@echo off

set /p location=Please enter location of .pdf files:

SETLOCAL ENABLEDELAYEDEXPANSION 
for /f "tokens=*" %%a in ('dir /b %location%\*.pdf') do (
set filename=%%~na

set file=%filename:~-8%
echo %file%
)

pause
1
  • 1
    Change the % characters on your last two commands inside the parentheses to ! characters. Commented Feb 1, 2018 at 12:55

2 Answers 2

1

As per my comment:

@Echo Off
:AskInput
ClS
Set "location="
Set /P "location=Please enter location of .pdf files: "
If Not Exist "%location%\*.pdf" GoTo AskInput

SetLocal EnableDelayedExpansion
For %%A In ("%location%\*.pdf") Do (Set "filename=%%~nA"
    Set "filename=!filename:~-8!"
    Echo !filename!)

Pause

I've replaced your For /F loop with a plain For loop, put a little bit of protection in there for the user input and removed the use of an additional variable, changing filename dynamically.

Sign up to request clarification or add additional context in comments.

Comments

0

Firstly, you enabledelayedexpansion but never use it. also %%~na will display name excluding extension. If the files all actually contains sub_ you can search and replace instead.

@echo off

set /p location=Please enter location of .pdf files:

SETLOCAL ENABLEDELAYEDEXPANSION 
for /f "tokens=*" %%a in ('dir /b %location%\*.pdf') do (
set "filename=%%~na"
set "filename=!filename:sub_=!"
echo !filename!
)
endlocal
pause

by doing for /?

%~I                     Expands %I which removes any surrounding 
                    quotation marks ("").
%~fI                    Expands %I to a fully qualified path name.
%~dI                    Expands %I to a drive letter only.
%~pI                    Expands %I to a path only.
%~nI                    Expands %I to a file name only.
%~xI                    Expands %I to a file extension only.
%~sI                    Expands path to contain short names only.
%~aI                    Expands %I to the file attributes of file.
%~tI                    Expands %I to the date and time of file.
%~zI                    Expands %I to the size of file.
%~$PATH:I               Searches the directories listed in the PATH environment 
                    variable and expands %I to the fully qualified name of 
                    the first one found. If the environment variable name 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.