Skip to content

Instantly share code, notes, and snippets.

@Akczht
Last active August 6, 2024 01:55
Show Gist options
  • Save Akczht/0ced3ac65971532e354d8c01bfa88223 to your computer and use it in GitHub Desktop.
Save Akczht/0ced3ac65971532e354d8c01bfa88223 to your computer and use it in GitHub Desktop.
A bulk file renaming script using bash, which renames files from a text file containing names
#!/bin/bash
directory="/path/to/your/directory"
names_file="/path/to/your/names.txt"
# Read new names into an array
new_names=()
while IFS= read -r line; do
new_names+=("$line")
done < "$names_file"
# Get a list of non-hidden files in the directory, sorted by name
files=($(ls -v "$directory" | grep -vE "^\."))
# Check if the number of files matches the number of new names
if [ "${#files[@]}" != "${#new_names[@]}" ]; then
echo "Number of files and names don't match."
exit 1
fi
# Determine number of digits for padding
num_files=${#files[@]}
num_digits=$(echo "${num_files}" | wc -m)
# Ask if user wants to add numbers and keep extensions
read -p "Add numbers to file names? (y/n): " add_numbers
read -p "Keep original file extensions? (y/n): " keep_extensions
# Rename files preserving extensions and optionally adding numbers
for ((i=0; i<${#files[@]}; i++)); do
old_file="$directory/${files[$i]}"
base_name="${new_names[$i]}"
ext="${files[$i]##*.}" # Extract extension
if [[ "$add_numbers" == "y" ]]; then
new_name=$(printf "%0${num_digits}d" $((i+1)))"-${base_name}"
else
new_name="$base_name"
fi
if [[ "$keep_extensions" == "y" ]]; then
new_name+="$ext"
fi
new_file="$directory/$new_name"
mv -i "$old_file" "$new_file"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment