I have been trying to investigate how to automate a script (shell or other) that periodically (once an hour for example) moves files with a constant naming convention to a folder (which is automatically created if not already there). The files are like this:
Camera1_01_20171213221830928.jpg
Camera1_01_20171213223142881.mp4
Basically it will be doing ‘housekeeping’.
I’m new to shell scripts, and I just can’t work out how to create a folder if it is not there (folder called 20171213 for example), then move the relevant files into it?
Any help would be greatly appreciated.
Advertisement
Answer
I finally went with a perl script which I could more easily trigger from a cron job:
#!/usr/bin/perl -w use strict; use Data::Dumper; use File::Copy; main(); sub main { my $dir = "/srv/NAS1/Camera1"; opendir(my $fh, $dir) or die("Could not open '$dir' for reading: $!n"); my @files = readdir($fh); closedir($fh); foreach my $file(@files) { if(-d $file) { next; # skip file if its a folder } if($file =~ /Camera1_01_(d{8})d{9}.(jpg|mp4)/) { my $date = $1; $date =~ /(d{4})(d{2})(d{2})/; my $folder = "$1-$2-$3"; # if the directory doesn't exist if(!(-e -d "${dir}/${folder}")) { mkdir("${dir}/${folder}"); } move("${dir}/$file","${dir}/${folder}"); } } }
Thanks for the contributions.