You are not logged in.
Is there a nice way to find filesystem objects by date(1)/strftime format?
In my backup script, I'm keeping a few old copies of each backup. Still, I'd like to configure the destination directory for each backup like e.g.
/backup/desktop-%Y%m%d
To find which existing backups there are, I need to search the file system for matching directory names. I haven't figured out a good way to do so, so I've settled with the following hackish script. It feels like there should be a better way, though. Is there?
#!/bin/bash
[[ -z $1 ]] && echo "Usage: $(basename $0) <pattern>" && exit 1
# Convert strftime sequences to wildcards
dir_glob=$(echo $1 | sed 's/%./*/g;s/*\+/*/g')
# First, match by wildcards
for cand in $(ls -d1 $dir_glob 2>/dev/null); do
# Second, make sure the wildcards were valid FORMATS
python -c "import time, sys; time.strptime('$cand', '$1'); sys.exit(0);" 2>/dev/null
[[ $? -eq 0 ]] && echo $cand
done
Example use:
find_by_strftime_format /backup/desktop-%Y%m%d
Last edited by halhen (2010-10-11 18:16:37)
Offline
You can use 'find / -type d -name <pattern>' or 'find / -type d -regex <pattern>' to look for some directories. Maybe you can use '-exec' instead of the loop.
The <pattern> 'date +%Y%m%d' is just 8 digits, with '20' being the first two, right?
Last edited by karol (2010-10-11 22:01:09)
Offline
The <pattern> 'date +%Y%m%d' is just 8 digits, with '20' being the first two, right?
Yeah, that's right. I don't want to enter a second configuration stating that %Y%m%d is eight digits. First and foremost since I hate unnescessary duplication and it should be possible to change formats without having to figure out a regular expression to go with it, but also since there are more rules than eight digits to the pattern. 20101355 is for example not a valid date.
Offline
If you're searching for a directory named e.g. 'desktop-20100603', you can use
find / -type d -regextype posix-extended -regex ".*desktop-2010(0[1-9]|10|11|12)(0[1-9]|(1|2)[0-9]|30|31)" \! -regex ".*desktop-2010(0(229|230|231|431|631|931)|1131)"
The search was I/O bound and took over a minute here. YMMV of course :-)
Edit: I hope the validation is OK now ;P
Last edited by karol (2010-10-11 23:15:54)
Offline