2

How do I loop through the files in the folder and parse the portion of the file name and store it in a variable + echo?

Folder contains following files and need to pull out the year:

Actual2015.txt
Actual2016.txt

What I tried:

for %%f in (*.txt) do (
set year=%%f:~7,4%
echo %year%
)

result should be:

2014

2015

2 Answers 2

2

you need delayed expansion:

setlocal enableDelayedExpansion
for %%f in (*.txt) do (
  set fname=%%nf
  set year=!fname:~6,4!
  echo !year!
)
Sign up to request clarification or add additional context in comments.

1 Comment

Missing the tilde.
1

Or you can take the last 4 characters of the file name if you know that last 4 are what you want.

@echo off
setlocal enableDelayedExpansion
for %%f in (*.txt) do (
  set fname=%%~nf
  set year=!fname:~-4!
  echo !year!
)
pause

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.