JSI Tip 7658. How do I copy one or more files to a single output file, excluding lines that contain specified text string(s)?


I have scripted CopyExclude.bat to copy one or more files to a single output file, while excluding lines that contain one or more search strings.

The syntax for using CopyExclude.bat is:

CopyExclude ExcludeFile OutputFile InputFile1 \[InputFile2 ... InputFileN\]

Where:

ExcludeFile   is a file that contains the search strings to exclude, one search string per line.

OutputFile    is the output file that will contain all the lines from all of the input files,
              excluding those lines that contain the search strings in ExcludeFile.

InputFileX    is one or more input files.
NOTE: CopyExclude.bat returns an ERRORLEVEL of 1 if the syntax is incorrect, or if ExcludeFile or InputFileX do NOT exist.

Sample Usage

If you use ListUserGroupPerms.bat to create a user permissions report on multiple drives, or folders, you can use CopyExclude.bat to combine the output files, and exlude lines that contain BUILTIN\Administrators and NT AUTHORITY\SYSTEM:
@echo off
CD C:\ReportFolder
ListUserGroupPerms \\Server1\UserProfiles report1.csv
ListUserGroupPerms \\Server2\UserHomeDirs report2.csv
@echo BUILTIN\Administrators>Exclude.txt
@echo NT AUTHORITY\SYSTEM>>Exclude.txt
CopyExclude Exclude.txt "%TEMP%\CopyExclude.tmp" report1.csv report2.csv 
sort "%TEMP%\CopyExclude.tmp" /O report.csv
del /q "%TEMP%\CopyExclude.tmp"
del /q report1.csv
del /q report2.csv
del /q exclude.txt

CopyExclude.bat contains:

@echo off
setlocal
IF \{%3\}

\{\} GOTO bad IF NOT EXIST %1 GOTO bad if NOT EXIST %3 GOTO bad set exc=%1 set out=%2 if exist %out% del /q %out% if exist "%TEMP%\CopyExcludeFile.tmp" del /q "%TEMP%\CopyExcludeFile.tmp" shift :loop shift if \{%1\}

\{\} goto exclude if NOT EXIST %1 goto bad @echo %1>>"%TEMP%\CopyExcludeFile.tmp" goto loop :exclude for /f "Tokens=*" %%f in ('findstr /i /l /v /f:"%TEMP%\CopyExcludeFile.tmp" /g:%exc%') do ( for /f "Tokens=1* Delims=:" %%O in ('@echo %%f') do ( @echo %%P>>%out% ) ) del /q "%TEMP%\CopyExcludeFile.tmp" endlocal exit /b 0 :bad @echo Usage: CopyExclude ExcludeFile OutputFile InputFile1 \[InputFile2 ... InputFileN\] @echo. endlocal exit /b 1



Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish