> I've got a shell script which takes files of various dates from
> multiple servers and dumps them all into one local directory.
> Now I need to make a script that sorts all of these files by date and
> moves them into a directory structure such as:
> /2005/December/
> /2006/January/
> /2006/February/
> etc.
> And here's the command I tried to piece together to accomplish this:
> mv . '(2005/12 ; 2006/01)' | date -d +%Y/%m
> MAN <command> isn't helping me figure out the syntax I need, and I
> can't find out how to do this online. My UNIX and LINUX books don't
> have any commands this complex, or even have much on the mv, stat, and
> date commands.
> This is why I need someone to point me in the right direction.
Ok, you want something like this, which assumes:
1) you are in the directory containing files you want to move
2) the directories you want to move the files to are subdirectories of the
current directory, and they already exist
3) you are using ksh or bash as your shell
# for all files in the current directory
for file in *
do
# if this isn't a file (i.e., a directory)
if [[ ! -f $file ]]
then
# continue to the next loop iteration
continue
fi
# set variable $date_stamp to last mod time of file
# stat returns a formatted time stamp and awk prints
# everything up to the 1st "."
date_stamp=$(stat $file -c '%y' | awk -F. '{print $1}')
# set variable $date_dir to a path name like "2005/December"
date_dir=$(date -d "$date_stamp" +%'Y/%B')
# move the file
mv $file $date_dir/$file
done
This could be cleaner and is UNTESTED, but should do what you want. This
demonstrates key shell constructs such as looping ( for; do; done ), test
evaluation ( if [[ ... ]] ), command substitution ( $(...) ), which is
capturing the output of a command, and using command pipelines ( ...|... ).
This should help, but you REALLY need to get a book on shell programming and
read it. I would recommend O'Reilly's "Learning the Korn shell" and/or
"Learning the bash shell".
If you are going to working regularly in Unix or Linux, I would also recommend
"Unix Made Easy", which is a 800-900 page book, but an excellent learning tool.
Kevin
--
Unix Guy Consulting, LLC
Unix and Linux Automation, Shell, Perl and CGI scripting
http://www.unix-guy.com