0

I browse directory and checking all files by for loop.

for %%f in (*.doc ) do (
  echo full name: %%f
  echo name without suffix: %%~nxf
)

For example files like this "1234-important.doc" I need somehow recognize what is between '-' and '.doc' and and set this value into variable flag to next processing.

IF [$flag] == [*"-important"*] (
  echo important
)

Do you have any suggestions how to do it ? Maybe use some regex on file name ?

4
  • I think that the forfiles feature is what you need. Commented Oct 3, 2018 at 12:08
  • Why do you not use for %%f in ("*-important*.doc") do ... to find and process only document files containing the string -important in file name? Commented Oct 3, 2018 at 12:22
  • @Mofi because in future there will be more flags than one and I want create universal script that will check this part of file name Commented Oct 3, 2018 at 13:02
  • 1
    @wdfeww, but you could easily add those to your FOR command. FOR %%f in (*-important.doc *-classified.doc *-sensitive.doc) do ...... Commented Oct 3, 2018 at 14:21

3 Answers 3

2

The following code works if there is only one hyphen in your file name. It uses a nested FOR command to split the base file name by the hyphen.

@echo off
for %%F in (*.doc ) do (
    echo full name: %%F
    echo name without suffix: %%~nF
    for /F "tokens=2 delims=-" %%G IN ("%%~nF") DO (
        IF /I "%%G"=="important" (echo File is important) else Echo File is not important
    )
)

This second set of code checks if the base file name ends in the string you are looking for by using the FINDSTR command. Conditional execution is then used to determine which echo command is executed. The double ampersand is used to execute if the previous command was successful. The double pipe is used to execute if the previous command was not successful.

for %%F in (*.doc ) do (
    set "flag="
    echo full name: %%F
    echo name without suffix: %%~nF
    echo %%~nF|findstr /E /I "important" >nul 2>&1 &&echo File is Important || echo file is not important
)
Sign up to request clarification or add additional context in comments.

Comments

0

Here an example where the filename is used too:

forfiles /M *important* /C "cmd /c echo @file : important"

Comments

0

Here is an example that searches for files containing a string. The STR variable can be set to whatever is being sought.

SET "STR=*-important*"
FOR /F "delims=" %%f IN ('DIR /B "%STR%" 2^>NUL') DO (
    ECHO %%~f
)

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.