14

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.

Adam S
  • 8,945
  • 17
  • 67
  • 103

2 Answers2

20

You can iterate over files with

for %x in (*) do ...

which is also a lot more robust than trying to iterate over the output of a command for this use case.

So

for %f in (A\*) do del "B\%~nxf"

or, if you need this in a batch file instead of the command line:

for %%f in (A\*) do del "B\%%~nxf"

%~nxf returns only the file name and extension of each file since it will be prefixed with A\ and you want to delete it in B.

Add > nul 2>&1 to 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:

for /f %x in ('some command') do ...

but there are several problems with doing this and in the case of iterating over dir output it's rarely necessary, hence I don't recommend it.


And since you are on Windows 7, you have PowerShell as well:

Get-ChildItem A\* | ForEach-Object { Remove-Item ('B\' + $_.Name) }

or shorter:

ls A\* | % { rm B\$($_.Name) }
Joey
  • 344,408
  • 85
  • 689
  • 683
  • 1
    you could add `-erroraction Silentlycontinue` to avoid the errors when some file in A don't exist in B – mjsr Jan 28 '12 at 19:53
  • Suppose I have a long list, how can I split the long line of elements in it? Example: `FOR %%G IN (11288211,38948621) DO ( )` – android developer Nov 23 '21 at 19:30
  • for /f %x in ('cmd /c "git branch | grep ^DE"') do echo %x - example for iterating over advance filtered list (top hit in google/bing). (where git is installed with option to include grep & other posix utils in file path). The pipe "|" in the command was difficult to get working. – TamusJRoyce May 31 '22 at 13:04
0
FOR /F %f IN ('dir /b /a-d A') DO del B\$f
Sammy
  • 1
  • 2