Search a string in a text file in batch script

GEEE picture GEEE · Jan 10, 2017 · Viewed 25.2k times · Source

How can I search a string in a text file line by line and when found a match, copy that whole line where the match was found into a variable?

Basically, I have a text file that contains the address/path of all sub-folders in a folder. I want to search for a string into this text file (the string will match only a part of a line) and if there is a match I want to copy into a variable that whole line.

The string comes from a file name and once there is a match in the text file I want to use the sub-folder address to move the file there.

This is what I have done until now:

@ECHO off
::Reads all the folders and subfolders existing in the "root1" folder and   writes the path for each foleder/subfolder into the "1.txt" file
dir /b /s /a:d "...\root1" > "...\1.txt"

::Reads all the files existing in "root2" folder and writes the path of each file into the "2.txt" file
dir /s /b "...\root2\" > "...\2.txt"

SETLOCAL EnableDelayedExpansion

::reads the last file path from the "2.txt" and asign it to a variable
for /f "delims=" %%x in (...\2.txt) do set Build=%%x
set "source=%Build%"
echo %source%

::from (...\...\...\...\a_b.txt) reads the name of the file (a_b.txt) without extension (a_b) and swap the  letter and outputs (b\a) into text file "7.txt"
FOR /F "tokens=6 delims=\" %%G IN (...\2.txt) DO echo %%G > ...\3.txt
FOR /F "tokens=1 delims=." %%G IN (...\3.txt) DO echo %%G > ...\4.txt
FOR /F "tokens=1 delims=_" %%G IN (...\4.txt) DO echo %%G > ...\5.txt
FOR /F "tokens=2 delims=_" %%G IN (...\4.txt) DO echo %%G > ...\6.txt
FOR /F %%G IN (...\5.txt) DO set "two=%%G"
FOR /F %%H IN (...\6.txt) DO set "one=%%H"
echo %one%\%two% > ...\7.txt

::assign the content (one line) from "7.txt" file to a variable
FOR /F %%G IN (...\7.txt) DO set "third=%%G"
echo %third% 

::should search the string from "third" variable in the "1.txt" and when found a match copy the respective line into a variable and put it into "8.txt"
FOR /F  %%a IN ('FINDSTR /x "%third%" ...\1.txt') DO set "xz=%%b"
echo %xz% > ...\8.txt

endlocal    

Answer

ProgrammersBlock picture ProgrammersBlock · Jan 10, 2017

You can accomplish this with a series of commands. You can use the command "find" to search a file and return the matching lines.

find "search term" fileToSearch > output.txt

Here, I've given a template command to search a file and redirect its output to a file.

Here is a previous article that shows how to read a file line by line in DOS. batch script - read line by line

for /f "tokens=*" %%a in (input.txt) do (
  echo line=%%a
  do something
)

I think for "do something" you would "move" the file to the directory and break out of the loop, possibly with a "goto label".