Monday, October 18, 2010

Automove files

There are a lot of utilities for automatically doing stuff with files. But I've never found any of them too useful. So I wrote this script. This python script will watch any number of directories for matching files and move them to corresponding directories.

Download here


It supports full regex matching of files and can do some basic renaming of target files. This is an example config file.

*~/Downloads*
.*\.(?:txt|docx?|pdf|odt|xlsx?)$ ~/Documents
[0-9]+\.(?:jpg|gif|png) ~/Dropbox/Misc/4chon

I'll go through line by line but it's fairly simple.

* * indicate which directory to watch. So *~/Downloads* watches /home/username/Downloads. I chose * * because regexes can't start with a *.

Next comes an ordered list of regexes and directories. When a file is created in ~/Downloads, the script will check that filename against the regexes that follow. Once it finds a match, it stops and uses that regex. Note: it does a regex MATCH. So the entire regex has to match the filename for it to be a match.

If there are no groups in the regex, it just moves the file from the watched directory to the new directory. So if you saved a file called document.doc in ~/Downloads, this script would move it to ~/Documents/document.doc.

If there IS a group in a regex, it will attempt to replace that group in the new file corresponding to (N). For example, if you saved document.txt in ~/Downloads, it would be moved to ~/Documents/falmarri-document.txt. Therefore you must keep track of which group corresponds with what number. This is standard regex behavior though, so I won't explain it here.

Because of these different formats for move, if you're not using grouping to replace filenames in the new file, you CANNOT have any groups in the regex. You MUST use (?:) to prevent the regex engine from naming the group.

So
[0-9]+\.(?:jpg|gif|png) ~/Dropbox/Misc/4chon
is legal, but
[0-9]+\.(jpg|gif|png) ~/Dropbox/Misc/4chon
is not. In fact, the latter will probably do some damage to your files since it will think 4chon is the new name of the file.

Finally, the default directory for your config file is ~/.move.conf. You can't specify a config file in this release, but it should be trivial to change if you don't want to wait for me.

As always, let me know of any errors

Download here

No comments: