Tuesday, June 29, 2010

Filter all lines of a text file with multiple strings list

To display only lines containing a string in a text file, easiest way is to use findstr commandline. For example, if we want to display lines containing "ok" (with /i switch for no case sensitivity) in a file file.txt we just to run at command line something like

type file.txt | findstr /i ok


With findstr you can also display lines NOT containing a particular string. For example you want all lines except line with string "not good" with this command

type file.txt | findstr /i /v /c:"not good"


Today my problem is that I need to report all administrators users of all computers except some users in a list.(yes, there is not SCCM or another tool which permit to do it here). I could do it like this:

type file.txt findstr /i /v /c:"administrator1" findstr /i /v /c:"administrator2" findstr /i /v /c:"administrator3"


But that's not really simple to maintain if you need to do some changes. Moreover, why do not do something which could be used for others problems of the same type?
So to do better than excel :) I created this batch file filter.cmd

@echo off
REM
REM Line Filter
REM By F.RICHARD
REM
REM created 2010 July
REM modified 2010 september for %1
REM

SET CURDIR=%~d0%~p0
cd /d %CURDIR%

IF {%1}=={} GOTO :ERRFILEINPUT
SET INPUTFILE=%1
echo Input file:%INPUTFILE%
If NOT EXIST %INPUTFILE% GOTO :ERRNEINPFILE
IF {%2}=={} GOTO :ERRFILEFILTER
SET FILTERFILE=%2
echo Filter file:%FILTERFILE%
If NOT EXIST %FILTERFILE% GOTO :ERRNEFILFILE
IF {%3}=={} GOTO :ERRFILERESULT
SET RESULTFILE=%3
echo Result file:%RESULTFILE%

setlocal EnableDelayedExpansion
set /a nbstr=0

Echo Begin filter
type %INPUTFILE% > tempfile!nbstr!.txt
for /F "tokens=*" %%i IN (%FILTERFILE%) Do (
set tmpfileread=tempfile!nbstr!.txt
set /a nbstr=!nbstr!+1
set tmpfileresult=tempfile!nbstr!.txt
type !tmpfileread! | findstr /v /i /c:%%i > !tmpfileresult!
del /f /q !tmpfileread!
)
move /Y !tmpfileresult! %RESULTFILE%
Echo End filter
goto :EOF

:ERRFILEINPUT
Echo.
Echo ERROR: you need an input filename
goto :Syntax

:ERRFILEFILTER
Echo.
Echo ERROR: you need a filter file
goto :Syntax

:ERRFILERESULT
Echo.
Echo ERROR: you need a result filename
goto :Syntax

:ERRNEINPFILE
Echo.
Echo ERROR: input file - %INPUTFILE% - does not exist in %CURDIR% directory
goto :EOF

:ERRNEFILFILE
Echo.
Echo ERROR: filter file - %FILTERFILE% - does not exist in %CURDIR% directory
goto :EOF

:Syntax
Echo.
Echo Syntax:
Echo %~nx0 inputfile filterfile resultfile
Echo.
goto :EOF


use it with something like

stringfilter.cmd input.txt filter.txt result.txt


With a input file like this input.txt

aaaaaaa
do not want to see it
bbbbbbb
not this one
ccccccc


This batch use a filter file like this filter.txt

"not this"
bbbbbbb
"not want"


and result file was like this result.txt

aaaaaaa
ccccccc


Et voilà

You can download this script
here

No comments: