I have a command line which copies files from folder A to folder B:
copy A\* B\
I would now like to delete all files in B that are present in A, non-recursively. I can list the files in A like this:
dir /b /a-d A
With the output being:
f0.txt
f1.txt
f2.txt
Here is the pseudocode for what I would like to do:
foreach $1 in <dir /b /a-d A output>:
del B\$1
Is there a windows command-line syntax that will execute a command, using the output of another command as an input? I am aware of the piping operator ( | ) but do not know of a way that this could be used to accomplish this task. Any help would be appreciate.
Restriction: Only commands available by default in Windows 7.
You can iterate over files with
which is also a lot more robust than trying to iterate over the output of a command for this use case.
So
or, if you need this in a batch file instead of the command line:
%~nxfreturns only the file name and extension of each file since it will be prefixed withA\and you want to delete it in B.Add
> nul 2>&1to suppress any output (error messages may appear when you try deleting files that don’t exist).Just for completeness, you can in fact iterate over the output of a command in almost the same way:
but there are several problems with doing this and in the case of iterating over
diroutput it’s rarely necessary, hence I don’t recommend it.And since you are on Windows 7, you have PowerShell as well:
or shorter: