If a file with the same name exists in Windows batch file movement, I would like to give it a serial number instead of overwriting it.

Asked 2 years ago, Updated 2 years ago, 34 views

What do you want to do in the end
·I want to move only specific extension files in the target folder (including subfolders) to the specified folder
·If a file with the same name exists, I would like to give it serial numbers instead of overwriting it

Tried
·I was able to confirm the movement of the batch file that moves specific files to the specified folder, but if a file with the same name exists, it will be overwritten to one file

Q
·If there is a file with the same name, I don't know how to add conditions by giving consecutive numbers instead of overwriting
·At what stage should the conditional branch be added if a file with the same name exists? When creating list.txt? Or when you're processing files one line at a time?

windows

2022-09-30 12:02

2 Answers

At what stage should the conditional branch be added if a file with the same name exists? When creating list.txt? Or when you're processing files one line at a time?

If you add a conditional branch when creating the list.txt, it will be overwritten if it is newly created before creating the file, so you should add it when you process it.

If there is a file with the same name, I don't know how to add conditions to add consecutive numbers instead of overwriting

Powershell is better suited for detailed operations such as obtaining serial numbers, so I made an example implementation with Powershell.

#Change and run the variable
Move-Mp3-Path "D:\test\src" - Dest "D:\test\dst" - IsMove$false

<#
.SYNOPSIS
 Move or copy files below the specified folder and add serial numbers if the file with the same name exists in the destination.

.DESCRIPTION
 A file of a specific extension is recursively acquired from a designated moving source folder and moved or copied to a designated output destination.
 If the same name file exists at the output destination, a serial number is added to avoid overwriting.
 A configuration of the moving source folder is not reproduced, but is directly moved or copied directly under the output destination folder.

.PARAMETER Path
 The path to the source folder.

.PARAMETER Dest
 The path to the destination folder to be moved or copied.

.PARAMETER FILTER
 Filters such as file names and extensions.
 "*.mp3" when omitted

.PARAMETER IsMove
 Move if $true or copy if $false.
 move when omitted

.NOTES
 Error if output destination folder does not exist.

#>
function Move-Mp3 {
    Param(
        [parameter(mandatory=$true)] [String] $Path,
        [parameter(mandatory=$true)] [String] $Dest,
        [String] $Filter="*.mp3",
        [bool] $IsMove=$true
    )

    ls-Path$Path-Filter$Filter-Recurse | foreach {
      $src=$_.FullName
      $name = $_.Name
      $target="${Dest}\${name}" 
      while(Test-Path$target){
        $f = [System.IO.Path]: GetFileNameWithoutExtension($name)
        $x = [System.IO.Path]: GetExtension($name)
        $r=[regex]"^(.*?)([0-9]+)$" 
        $m = $r.Match($f)
        if($m.Success){
          # Count up the last number
          $index=[int]$m.Groups[2].Value+1
          $name="{0}{1}{2}"-f$m.Groups[1].Value, $index,$x
        } else{
          # If there is no number at the end, add "-1" before the extension
          $name="{0}-1{1}"-f$f,$x
          $index++
        }
        $target="${Dest}\${name}" 
      }
      if($IsMove){
        move$src$target
        US>"$src moved to $target."
      } else{
        copy$src$target
        US>"$src copied to $target."
      }
    }
}

At first, I tried to implement it as a bat file, but I was frustrated because extracting serial numbers was troublesome.
If you want to see the bat file even if it's a half-baked implementation, please refer to the answers before the revision from the history.


2022-09-30 12:02

Git Bash is recommended because there are more Bash users than PowerShell users, so you can gain more knowledge.Perl is also included in the Git Bash.With Perl, you can do the whole thing.

For example, D:\test contains subdirectories called A and B.In Git Bash, D:\test is written as /d/test, so enter cd/d/test/.

Now consider aaa.txt, aaa.bin, bbb.txt, ccc.txt, ccc.txt, ccc.out, and move to B.txt.

Prepare the following Perl script file: move.pl

use warnings;
use File::Copy 'move';

$srcdir="./A";# Source Directory
$dstdir = "./B";# Destination Directory
$ext="txt";# extension

openir(from,$srcdir);
foreach(readdir(FROM)) {
    next if$_!~/^(.*)\.${ext}$/;
    $original=$1;#Original filename (no extension)
    if (-f"${dstdir}/${original}.${ext}"){
        $filename="${original}.${ext}";
    } else{
        $i = 1;
        while (-f"${dstdir}/${original}_${i}.${ext}"){
            $i++;
        }
    $filename="${original}_${i}.${ext}";
    }
    print "${srcdir}/${original}.${ext} to ${dstdir}/${filename}";
    move("${srcdir}/${original}.${ext}", "${dstdir}/${filename}";
}
closedir (from);

Run this script within the Git Bash /d/test/.The execution commands are as follows:

perl move.pl

When you run it, you will see the following:

Move ./A/aaa.txt to ./B/aaa.txt
Move ./A/bbb.txt to ./B/bbb_3.txt
Move ./A/ccc.txt to ./B/ccc_1.txt

In fact, only aaa.bin, ccc.out, and aaa.txt, bbb.txt, bbb.txt, bbbbb.txt, bbbbb.txt, bbbb.txt, .txt


2022-09-30 12:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.