Issue
I am trying to run a bash script using the find
command on a terminal in osx and getting an error rename_file: command not found
. I am including the script I wrote below. Is there an issue with the way I am calling the function when I execute find
?
My goal is to then organize these files into specific directories by month, but I haven't gotten that far as the error is holding me up.
Thanks for any tips as to what I am doing wrong!
#!/bin/bash
base_dir="."
# Function to rename files based on their creation date
rename_file() {
local file="$1"
local file_prefix
local year
local month
local day
# Get the creation date of the file
creation_date=$(stat -f "%SB" -t "%Y%m%d" "$file")
# Extract year, month, and day from the creation date
year=${creation_date:0:4}
month=${creation_date:4:2}
day=${creation_date:6:2}
# Construct the new filename
file_prefix="${year}_${month}_${day}_"
new_filename="${file_prefix}$(basename "$file")"
# Rename the file
echo "$file" "$(dirname "$file")/$new_filename"
#mv "$file" "$(dirname "$file")/$new_filename"
}
# Find and process files in the base directory and its subdirectories
find "$base_dir" -type f -exec bash -c 'rename_file "$0"' {} \;
echo "File renaming completed."
Solution
Replace your last 3 lines with these, it will work
export -f rename_file
find . -type f -exec bash -c 'rename_file "$@"' {} +
echo "File renaming completed."
Answered By - Francesco Gasparetto Answer Checked By - Candace Johnson (WPSolving Volunteer)