Hello,
I have a Bash shell script that works fine when I run it from the command line with a proper path to the folder or file I'm trying to operate on. It changes a file's name based on the date found in its PDF text.
When I run it from the "Run shell script" in Hazel, it fails. When I run it using Preview Rule, it responds, "Rule Does Not Match."
I think it's a path error, but I also think I'm using 1 correctly. Can anyone help?
Here it is:
#!/bin/bash
# Function to process a single PDF
process_pdf() {
pdf_file="$1"
# Extract text from the PDF using pdftotext and clean up spaces and line breaks
text=$(pdftotext -layout "$pdf_file" - | tr '\n' ' ' | tr -s ' ')
# Search for "Pay Start Date" followed by a date in MM/DD/YYYY format
date_match=$(echo "$text" | grep -Eo 'Pay[[:space:]]*Start[[:space:]]*Date[[:space:]]*[0-1][0-9]/[0-3][0-9]/[0-9]{4}' | grep -Eo '[0-1][0-9]/[0-3][0-9]/[0-9]{4}' | head -n 1)
if [[ -z "$date_match" ]]; then
echo "No 'Pay Start Date' found in $pdf_file"
return
fi
# Convert MM/DD/YYYY to YYMMDD
month=${date_match:0:2}
day=${date_match:3:2}
year=${date_match:6:4}
formatted_date="${year:2:2}${month}${day}"
# Generate the new file name
dir=$(dirname "$pdf_file")
base=$(basename "$pdf_file" .pdf)
new_file="$dir/PayStub $formatted_date.pdf"
# Rename the file
mv "$pdf_file" "$new_file"
echo "Renamed $pdf_file to $new_file"
}
# Check if a folder or file was passed as an argument
if [[ -d "$1" ]]; then
# Process all PDF files in the folder
for pdf in "$1"/*.pdf; do
process_pdf "$pdf"
done
elif [[ -f "$1" ]]; then
# Process the single PDF file
process_pdf "$1"
else
echo "Usage: $0 /path/to/folder/or/pdf"
fi