options for [for /f "usebackq" %%f in (`find "" path`) do] sentence in batch

Solution 1:

Here, only the last match is selected because res is overwritten each time. This will save all the matches delimiting them with space:

@echo off & setlocal enabledelayedexpansion & set "fruits=" 
for /f ^tokens^=^* %%a in ('type list.txt ^| find "a"') do set "fruits=!fruits! %%a"
set "fruits=!fruits:~1!

Now echo !fruits! will give apple pear mango.

If you want to get first two matches use this:

for /f "tokens=1,2 delims= " %%a in ("!fruits!") do echo %%a %%b

will give apple pear and to save it in fruits use do set "fruits=%%a %%b". You can modify tokens to select the words delimited by space.

Solution 2:

@Echo off

<con: CD /d "%~dp0" && Setlocal EnableDelayedExpansion
for /f %%i in (list.txt)do echo\%%i|find "a" >nul && (
   set /a "_cnt+=1+0" && call set "_res_!_cnt!=%%~i" )

for /l %%L in (1 1 !_cnt!)do echo\_res_%%L==!_res_%%L!
endlocal
  • Output:
_res_1==apple
_res_2==pear
_res_3==mango

You can use a for /f loop and an echo\"a"|find "a" if "a", is found, the operator && will continue, and a counter will be used to define a variable_counter_actual=current_occurrence, so that you can make use of any occurs between 1st and last.

For usage example, you have the output of the for /l loop, which will list all occurrences starting at 1, following from 1 in 1 to the total (!_cnt!), each !_res_%%L!.

  • For only the first two occurrences:
for /l %%L in (1 1 2)do echo\_res_%%L==!_res_%%L!
  • Use only the occurrences you want, for example 1st and 3rd:
for %%L in (1,3)do echo\_res_%%L==!_res_%%L!
  • Or, simply use:
echo\!_res_1!
echo\!_res_2!