Batch - Inverse/Negative FOR loops?
I'm trying to concatenate many files into two individual files.
The first file will be a concatenation of all other files with "bob" in the filename. The second file will be a concatenation of all files WITHOUT "bob" in the filename. Both files will output the name of the file before actually doing the concatenation.
Here's what I have so far:
@echo off
setlocal EnableDelayedExpansion
set bob=All_bob.txt
set jimmy=All_jimmy.txt
if exist %bob% del %bob%
if exist %jimmy% del %jimmy%
for %%a in (*bob*.txt) do (
echo /* >>%bob%
echo * %%a >>%bob%
echo */ >>%bob%
copy/b %bob%+"%%a" %bob%
echo. >>%bob%
echo. >>%bob%)
for %%a not in (*bob*.txt) do (
echo /* >>%jimmy%
echo * %%a >>%jimmy%
echo */ >>%jimmy%
copy/b %jimmy%+"%%a" 开发者_运维问答%jimmy%
echo. >>%jimmy%
echo. >>%jimmy%)
However, the second FOR loop (at the bottom) doesn't want to play nice using "not", and using an exclamation point like this...
for %%a !(*bob*.txt) do (
...doesn't want to work, either. So how do I concatenate files that do NOT contain what is inside the parenthesis?
I don't think there is a clean solution to this.
You could probably use FINDSTR to filter %%a but that would require turning *bob*.txt
into a regular expression and that is probably not easy to automate.
Another (ugly) solution is to use nested loops:
echo bob:
for %%a in (*bob*.txt) do (
echo %%a
)
echo not bob:
for %%a in (*) do (
setlocal ENABLEDELAYEDEXPANSION&set inc=1
for %%b in (*bob*.txt) do if "%%~a"=="%%~b" set inc=0
if "!inc!"=="1" echo %%a
endlocal
)
How about using find:
for /F %%a in ('dir /b *.txt') do (
echo %%a | find /V "bob")
This should return all .txt files that don't have "bob" in them.
Using findstr
and a regular expression for *bob*.txt
:
for /f "usebackq delims=" %%a in (`dir /b ^| findstr ".*bob.*\.txt"`) do (…)
Just use the /V
switch to process all other files:
for /f "usebackq delims=" %%a in (`dir /b ^| findstr /v ".*bob.*\.txt"`) do (…)
You can use the help
command or the /?
switch for for
or findstr
for more information.
I cleared the delimiters (delims=
) to allow for spaces in the filenames.
精彩评论