Forfiles Command Windows cmd - forfiles which contain 2 or more string snippets in filename do something

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

In Windows CMD, you can use the forfiles command along with wildcards and conditional statements to process files that contain multiple string snippets in their filenames. Here's an example:

batch
@echo off
setlocal enabledelayedexpansion

set "folder=C:\Path\to\folder"
set "snippet1=string1"
set "snippet2=string2"

forfiles /p "%folder%" /m "*%snippet1%*%snippet2%*" /c "cmd /c if @isdir==FALSE (echo Do something with @file)"

In this example:

  1. Set the folder variable to the path of the folder containing the files you want to process.

  2. Set the snippet1 and snippet2 variables to the desired string snippets that should be present in the filenames.

  3. The forfiles command is used with the /p option to specify the folder to search in, and the /m option to define the wildcard pattern for filenames.

  4. Inside the /c option, the if statement checks if the item is not a directory (@isdir==FALSE). This ensures that only files (not directories) are processed.

  5. The echo Do something with @file command within the if statement specifies the action to be performed on each matching file. Replace it with your desired command or action.

By using the forfiles command with wildcard patterns and the if statement, you can process files that contain multiple string snippets in their filenames. Adjust the folder, snippet1, snippet2, and the action inside the if statement according to your specific requirements.

Note that the /m option in forfiles uses wildcards to match filenames. You can modify the wildcard pattern to suit your specific needs, such as adjusting the position or order of the string snippets.