0

The file I want to work with is in C:\folder1\subfolder2 but has a file basename containing a variable date, i.e. company_yyyyMMdd.zip

I want to define a variable named fileyear, by searching C:\folder1\subfolder2\company*.zip, containing the four digit year string.

So far my code is:

@echo off
setlocal
for /f %%a in ("C:\folder1\subfolder2\company*.zip") do set fileyear=%%a:~7,4% & echo %fileyear%

I expect echo %fileyear% to output 2022

I did a test in like this:

set FILENAME=company_20221215.zip
echo %FILENAME:~7,4%

It said 2022 just like I wanted.

7 means start at the 7th position and the 4 means read the next 4 digits.

  • Always use a `setlocal` following the `@echo off` as it disposes of changes to the environment when the batch terminates. You cannot substring metavariables like `%%a`. You nrrd to assign them first to a user-variable. You also need to beware of the [delayed expansion trap](https://stackoverflow.com/a/30284028/2128947). – Magoo Mar 19 '23 at 22:53
  • There is absolutely no need ever to use a single line in a batch file. It doesn't make the code any more efficient, nor does it make it simpler to read. It would also be better to use `company_*.zip`, and even better `company_????????.zip`, as your wildcard/glob – Compo Mar 20 '23 at 01:10
  • What change do I need to make to my code so it outputs 2022? – Online Statements Mar 20 '23 at 06:20
  • The advice for which changes you need to make has already been given. We aren't here to do it for you, please make an attempt. – Compo Mar 20 '23 at 10:20

0 Answers0