htan68
htan68

Reputation: 33

Batch file to parse text file line by line then check if that line exist in other text files

This is my first post, asking permission to ask for help here.

I have a limited knowledge with batch file. I have a script that uses FOR /f that reads a text file with one word per line then use that word as my variable.

Problem is I wanted to use that variable (each line from reference file) to check if that variable exist on all target text files, now I have no idea how to create a batch file for this purpose. I spent time searching for an answer but cannot find any, should there be a similar batch file here in StackOverflow, please give me the link.

Goal: Count how many PC have the packages from reference file packageList.txt. I already gathered the list of packages on all PC and saved them as PC1_bare.txt, PC2_bare.txt, PC3_bare.txt and so on...

Example:

My text files are...

packageList.txt

Acrobat

Chrome

Flash

Photoshop

msOffice

Contents of PC1_bare.txt:

Acrobat

Chrome

Flash

Photoshop

msOffice

Contents of PC2_bare.txt:

Acrobat

Chrome

Flash

msOffice

Contents of PC3_bare.txt:

Acrobat

Flash

msOffice

Contents of pcList:

PC1_bare.txt

PC2_bare.txt

PC3_bare.txt

Expected results:

Acrobat is installed to 3 PC

Chrome is installed to 2 PC

Flash is installed to 3 PC 

Photoshop is installed to 1 PC

msOffice is installed to 3 PC

Upvotes: 0

Views: 2853

Answers (2)

Magoo
Magoo

Reputation: 80033

@ECHO OFF
SETLOCAL

:: make a tempfile
:maketemp
SET "tempfile=%temp%\%random%"
IF EXIST "%tempfile%*" (GOTO maketemp) ELSE (ECHO.>"%tempfile%a")

FOR /f "delims=" %%p IN (pclist.txt) DO (>>"%tempfile%a" TYPE "%%p")
FOR /f "delims=" %%p IN (packagelist.txt) DO (
 FOR /f "delims=" %%c IN ('findstr /i /b /e /L /c:"%%p" "%tempfile%a"^|find /c /v ""') DO echo %%p is installed to %%c PC
)
DEL /Q "%tempfile%a"

GOTO :EOF

Make a temporary file.
concatenate the lists of files found into that file.
for each package, find the packagename as a /L (literal) that both /b and /e (begins and ends) a line, /i ignoring case /c: "spaces may appear in the packagename", then FIND and count (/c) the number of not empty (/v "") lines produced and show this count along with the packagename.

(Also works with 'installed on 0 PCs')

Upvotes: 0

unclemeat
unclemeat

Reputation: 5197

This should do the trick -

for /f "delims=" %%a in (packageList.txt) do (
    set count=0
    for /f %%b in (pcList) do for /f %%c in (%%b) do if "%%c"=="%%a" set /a count+=1
    echo %%a is installed to !count! PCs
)

Upvotes: 1

Related Questions