简体   繁体   中英

Batch- how to parse .txt file and find words in it

I need to go through a a.txt file line by line and extract and copy the words zzz and yyy from it, store them in another b.txt file than loop through these words and create a command lines that looks like this :

blabla XXX

while XXX is taken one by one from the b.txt file we created before that got "zzz" and "yyy" in it.

example:

file a.txt

jsdfjdsfnsdj

yyy

sdfdsfsd

zzz

b.txt file will be:

yyy

zzz

and the commands created will be:

blabla yyy

blabla zzz

use For /F for read line and check line with findstr

for /F "delims=" %%a in (a.txt) do ( call :checkline %%a )
goto :eof

:checkline 
@echo %1 |findstr /g:b.txt

if %ERRORLEVEL%==0 echo blablabla  %1 >>c.txt
ENDLOCAL

:eof
@echo off
if exist b.txt del b.txt
for /f "delims=" %%a in (a.txt) do (
    if "%%a"=="yyy" echo blabla %%a >> b.txt
    if "%%a"=="zzz" echo blabla %%a >> b.txt
)

I think you can make @Eric's approach work too. findstr is better if you actually place your search expression in the pattern file. And I think his approach should be amended to match the entire line.

echo ^^yyy^$>  patterns.txt
echo ^^zzz^$>> patterns.txt
for /F "delims=" %%a in (a.txt) do (call :checkline %%a)
del patterns.txt
goto :eof

:checkline 
@echo %1 | findstr /g:patterns.txt
if %ERRORLEVEL%==0 echo blablabla %1 >>c.txt
goto :eof

I think you could possibly use this line without the extra hassle of pattern file. Unfortunately findstr doesn't truly support alternation in regular expressions but I think this works ok.

@echo %1 | findstr "^yyy$ ^zzz$"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM