How to Move Old File to Another Folder

Commands to move folders and files within of a certain age to another Directory

forfiles executes the command line after the /C option with the currently iterated directory as the working directory. This is also true with the /S option.

The reference @file returns the pure (quoted) file name; the reference @relpath returns a path relative to the given root (behind the /P option, which defaults to the current directory).

So you could try something like this (note that the cmd /C prefix is required for cmd-internal commands like move, echo or if; the upper-case ECHO just displays the move command line that would be executed without):

forfiles /S /D -90 /C "cmd /C if @isdir==FALSE ECHO move @relpath 0x22C:\temp\0x22"

This would move all files into the directory C:\temp, losing the original directory hierarchy however. (Note that the if @isdir==FALSE query prevents sub-directories from being processed.)

Therefore we need to build the destination directories on our own, like this:

forfiles /S /D -90 /C "cmd /C if @isdir==FALSE (for %F in (@relpath) do @(2> nul mkdir 0x22C:\temp\%~F\..0x22 & ECHO move @relpath 0x22C:\temp\%~F0x22))"

What happens here:

  • in general, 0x22 represents a quotation mark ";
  • if @isdir==FALSE ensures to process files only;
  • the for loop just removes surrounding quotes from the path retrieved by @relpath when accessed by %~F; ensure to double the % signs in case you are using the code in a batch file!
  • mkdir creates the parent directory of the currently iterated item; 2> nul hides the error message in case the directory already exists;
  • move is preceded by ECHO for testing purposes; remove it to actually move files;

If you want to overwrite files in the destination location, simply add the /Y option to move.


The following command line might also work for the sample path, but it is going to fail for sure in case the destination path contains SPACEs or other poisonous characters, because quotation is not properly handled:

forfiles /S /C "cmd /C if @isdir==FALSE (2> nul mkdir C:\temp\@relpath\.. & ECHO move @relpath C:\temp\@relpath)"

File move to another folder laravel

Problem

The problem is, you don't have files to move.

$newDirectoryPath = storage_path('logs/old-log-' . $days);

if (!\File::isDirectory($newDirectoryPath)) {
\File::makeDirectory($newDirectoryPath);
}

The move() method may be used to rename or move an existing file to a new location. But
$newDirectoryPath is a folder not a file.


Solution

You need to change :

\File::move(
$path . $file['basename'], // old file
$newDirectoryPath . '/' . $file['basename'] // new file
);
public function logs()
{
$today = \Carbon\Carbon::today()->format('Y-m-d');
$days = \Carbon\Carbon::today()->subDays(7)->format('Y-m-d');

$newDirectoryPath = storage_path('logs/old-log-' . $days);
if (!\File::isDirectory($newDirectoryPath)) {
\File::makeDirectory($newDirectoryPath);
}

$path = storage_path('logs/');
$allFiles = \File::allFiles($path);

foreach ($allFiles as $files) {
$file = pathinfo($files);
$logDay = str_replace('laravel-', '', $file['filename']);

if ($logDay >= $days && $logDay < $today) {
\File::move($path . $file['basename'], $newDirectoryPath . '/' . $file['basename']);
}

}
}

Windows Script to move files older than 30 days with a specific extension to another folder

Since you tagged your question with batch-file, I suppose you are accepting batch file solutions too.

Here you are:

pushd \\folder1
forfiles /M *.doc /D -30 /C "cmd /C if @isdir==FALSE move @file .\archive\"
forfiles /M *.xls /D -30 /C "cmd /C if @isdir==FALSE move @file .\archive\"
popd

Due to the syntax you used for the source directory path (\\folder1\) I suppose it is given by a UNC path. So I use the pushd command which understands such, maps it to a temporary drive it creates and changes the current working directory to the root of that drive.

The forfiles command is capable of enumerating a given directory (tree) and iterates through all items that meet a certain mask and modification date (age). Since forfiles supports a single mask only, I simply use it twice.

The popd command at the end removes that temporary drive which has been created by pushd.

For more details about each used command, type it into the command prompt, followed by /?.

How to move old file to another folder

ls -l | awk '{print $NF}' | awk 'substr($0, length($0)-9, length($0)) < "2012-08-20" {system("mv "$0" /old/")}'

This will move all the files older than "2012-08-20" to the folder "/old". Likewise, you can change the "2012-08-20" to specify particular date you want. Note this assumes that the file suffix is a date stamp, but the prefix can be any name.

If you just need to move files older than a certain days, then I think rkyser's answer is better for that.

Python move files older than 7 days but keep the most recent ones

Here is an example of how I would do it.

from re import match
from os import listdir, remove
from os.path import getctime, isfile
from datetime import timedelta, datetime as dt

def time_validator(days):
delta = dt.now() - timedelta(days)
return lambda x: dt.fromtimestamp(getctime(x)) > delta

def files_to_remove(n):
validate = time_validator(7)
files = sorted([
y for x in listdir('/etc')
if isfile((y := f'/etc/{x}'))
and validate(y)
and match('sudoers\.(?!rpm).*', y)
], key=lambda x: getctime(x))
return files[-n:] if len(files) > 20 else []

def remove_files(files):
for file in files: remove(file)

if __name__ == '__main__':
remove_files(files_to_remove(10))

How do I move a file from one location to another in Java?

myFile.renameTo(new File("/the/new/place/newName.file"));

File#renameTo does that (it can not only rename, but also move between directories, at least on the same file system).

Renames the file denoted by this abstract pathname.

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

If you need a more comprehensive solution (such as wanting to move the file between disks), look at Apache Commons FileUtils#moveFile



Related Topics



Leave a reply



Submit