在批处理脚本中搜索文本文件中的字符串

时间:2017-01-10 12:27:53

标签: batch-file string-search text-search

如何逐行搜索文本文件中的字符串,找到匹配项后,将找到匹配项的整行复制到变量中?

基本上,我有一个文本文件,其中包含文件夹中所有子文件夹的地址/路径。我想在这个文本文件中搜索一个字符串(字符串只匹配一行的一部分),如果有匹配,我想复制到整行的变量。

字符串来自文件名,一旦文本文件中有匹配项,我想使用子文件夹地址将文件移动到那里。

这是我迄今为止所做的事情:

@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    

1 个答案:

答案 0 :(得分:1)

您可以使用一系列命令完成此操作。 您可以使用命令“find”搜索文件并返回匹配的行。

find "search term" fileToSearch > output.txt

在这里,我给出了一个模板命令来搜索文件并将其输出重定向到文件。

这是上一篇文章,展示了如何在DOS中逐行读取文件。 batch script - read line by line

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

我认为对于“做某事”你会将文件“移动”到目录并突破循环,可能带有“转到标签”。