Implement shell script to extract date from file contents in Automator
I've hacked together a bash script that I'm testing on a folder of .eml files. It extracts the first instance of a date string such as "30/01/15" from within the email, reformats the string to "15-01-30" and adds it to the beginning of the filename separated by an underscore.
for f in *.eml; do
date=`grep -o -m 1 '..\/..\/..' "$f" | awk -F "/" '{print $3"-"$2"-"$1}'`
name="${f%.*}"
ext="${f##*.}"
mv "$f" "${date}_${name}.$ext"
done
It works for the most part. On my test folder I got a few files named with garbled date output like "dm-4X-UG" but I haven't looked into that yet.
Main question: how do I go about implementing this as an automator service? I'd like to be able select files (.eml and .pdf mostly) that I know have this date format in the finder and run the script as a service. Can't seem to get it right.
Also, any suggestions for improving this? Not sure if it's the most efficient / safest script. I'd eventually like to write a bunch of these for some common date formats that show up in my email or OCR pdf receipts.
Thanks!
MacBook Pro with Retina display, OS X Yosemite (10.10.3)