简体   繁体   中英

Command line how to search a string into a %% variable

I have a text file including filename specifications formatted as following, filename-yyyymmdd

source.txt

IMG-20190601
IMG-20190602
IMG-20190603
...

I want to read this file in order to compare the dates with a reference date and do some action depending the result. IMG is always the same, only the date is changing.

For this purpose I am trying to find the filename date into each line I am reading to compare it with today.

I did not succeed to find the right syntax, I found that extracting a substring can be done with

set SUBSTRING=%VAR:~POSITION,SIZE% 

but it is not working with %%variable type.

Any help is welcome.

My code:

set comparedate=20190702
set /A i=0
for /F "usebackq delims=" %%a in (source.txt) do (
    set /A i+=1
    rem call echo %%i%%
    rem call echo %%a
    set datefile=%%a:~4,8 # the line that is not working
    if %datefile% geq %comparedate%  (goto here) else (goto there)
    :here
    echo do something
    :there
    echo do something else
)

Implemented my suggestions from the comments to your code. Also avoided delayed expansion by using the tokens directly (together with another method to get the date string from the filenames (by splitting at the hyphen)):

@echo off
set comparedate=20190702
set /A i=0
for /F "tokens=1,* delims=-" %%a in (source.txt) do (
    ECHO FileDate=%%b
    ECHO FileName=%%a-%%b [in case you need it]
    if "%%b" geq "%comparedate%"  (
      echo do something
    ) else (
      echo do something else
    )
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM