Roy
Roy

Reputation: 1225

How to search a string in a file?

I am writing a batch file to read all the files within the folder.

Below is my code:

@echo off
setlocal EnableDelayedExpansion 
for %%I in (C:\test\*.print_job.*) do (
   Set Name=%%~nxI
   echo !Name!
)
pause

I am able to get all the .print_job files but now I want to read all the files and look for a specific identifier.

Thanks in advance

Upvotes: 1

Views: 114

Answers (2)

michael_heath
michael_heath

Reputation: 5372

@echo off
rem             string  target                  destination
call :movefiles "MOUNT" "C:\test\*.print_job.*" "C:\Folder1"
call :movefiles "PROD"  "C:\test\*.print_job.*" "C:\Folder2"
call :movefiles "SPI"   "C:\test\*.print_job.*" "C:\Folder3"
goto :eof

:movefiles
if not exist "%~3" md "%~3"
for /f "delims=" %%A in ('2^>nul findstr /l /m /c:"%~1" "%~2"') do (
    move "%%~A" "%~3"
)
goto :eof

Use of call :movefiles to handle each of the 3 strings to search for in the target files.

Call syntax: call :movefiles <string> <target> <destination>

Makes the destination directory if not exist. If string found in a target file, the file will be moved into the destination folder.

The findstr arguments used are:

  • /l Uses search strings literally.
  • /m Prints only the filename if a file contains a match.
  • /c:string Uses specified string as a literal search string.

You can insert rd "%~3" after the for loop if you want to remove empty destination folders.


To loop every 2 seconds:

@echo off
:main
rem             string  target                  destination
call :movefiles "MOUNT" "C:\test\*.print_job.*" "C:\Folder1"
call :movefiles "PROD"  "C:\test\*.print_job.*" "C:\Folder2"
call :movefiles "SPI"   "C:\test\*.print_job.*" "C:\Folder3"
timeout /t 2 /nobreak >nul
goto :main

:movefiles
if not exist "%~3" md "%~3"
for /f "delims=" %%A in ('2^>nul findstr /l /m /c:"%~1" "%~2"') do (
    echo move "%%~A" "%~3"
)
goto :eof

You may need to use Ctrl+C to end the script as it is in a continuous loop.

If you can use a task scheduler instead then that could work.

Upvotes: 1

user6811411
user6811411

Reputation:

If a file name with the search word removed is different it had been in there.

@echo off
for %%I in (C:\test\*) do Call :Sub "%%I"
Pause
Goto :Eof
:Sub
Set "Name=%~nx1"
if "%Name%" neq "%Name:MOUNT=%" (move "%~1" "C:\Folder1\" & Goto :Eof)
if "%Name%" neq "%Name:PROD=%"  (move "%~1" "C:\Folder2\" & Goto :Eof)
if "%Name%" neq "%Name:SPI=%"   (move "%~1" "C:\Folder3\" & Goto :Eof)

Upvotes: 1

Related Questions