关于批处理中使用FIND指令存储搜索结果到变量的技术咨询
Got it, let's fix up your batch script to reliably grab that occurrence count. The find /c command outputs a line like ---------- "C:\FORTEST\CBL001.cbl": 5 (where 5 is your count), so we need to extract that final number cleanly—especially important if your filenames have spaces, which would break simple token splitting. Also, grabbing just the rightmost character would fail if the count is multi-digit, so we'll use a more robust method.
Here's a solution that works for all file names and recursively checks subfolders:
@echo off setlocal enabledelayedexpansion :: Configure your search parameters here set "targetString=PROGRAM-ID." set "rootDirectory=C:\FORTEST" set "filePattern=*.cbl" :: Recursively loop through all matching files for /r "%rootDirectory%" %%F in (%filePattern%) do ( :: Capture the full output of find /c for /F "delims=" %%A in ('find /c "%targetString%" "%%F"') do ( set "findOutput=%%A" :: Extract the count by removing everything up to the last ": " set "occurrenceCount=!findOutput:*: =!" :: Now you can use !occurrenceCount! for your后续操作 echo Found !occurrenceCount! instances of "%targetString%" in "%%F" :: Example: if count is greater than 0, run your custom logic if !occurrenceCount! gtr 0 ( :: Add your specific operations here ) ) ) endlocal
Key Details:
- Delayed Expansion: We enable
enabledelayedexpansionbecause we're modifying and reading variables inside nested loops—without this, the variable values won't update correctly during loop execution. - Robust Count Extraction: The line
set "occurrenceCount=!findOutput:*: =!"uses batch string substitution to strip everything from the start of the output up to the first:, leaving only the numeric count. This works even if your file paths have spaces or special characters, and handles multi-digit counts (which grabbing just the rightmost character wouldn't do). - Recursive Search: The
for /rcommand automatically traverses all subfolders under your root directory, so you don't have to handle subfolder navigation manually.
If you only need to check a single file (like your original example), you can simplify it to:
@echo off setlocal enabledelayedexpansion set "targetString=PROGRAM-ID." set "targetFile=C:\FORTEST\CBL001.cbl" for /F "delims=" %%A in ('find /c "%targetString%" "%targetFile%"') do ( set "findOutput=%%A" set "occurrenceCount=!findOutput:*: =!" ) echo Count of "%targetString%" in file: !occurrenceCount! endlocal
That should give you the clean numeric count you need to work with for your后续操作.
内容的提问来源于stack exchange,提问作者HanSoloQue

