Bash script to rename files given a text file with new filenames

Yesterday I found myself needing to rename a bunch of files given a text file with the new names, so I had to use some of my (few) bash skills. I’m sure I could have done it in fewer lines, but the bash script below did the job.

#!/bin/bash

# v1.1
# USAGE:
# ./rename.sh text.txt *.dat

if [ "$#" == "0" ]; then
    echo "./rename.sh names.txt \"*.dat\""
    exit 1
fi

namefile=$1
shift

# read file line by line, store in array with leading number and .mp3 postfix
index=0
while read line; do
	fileNum=`printf "%02d" $((index+1))`
	names[index]="$fileNum. $line.dat" # Custom rename format
	((++index))
done < $namefile

namecount=${#names[@]}

if [ "$#" -ne "$namecount" ]; then
	echo "Number of files ($#) doesn't match number of lines in $namefile ($namecount)"
	exit 1
fi

# rename input files to match lines in the array
index=0
files=("$@")
for file in "${files[@]}" ; do
	file=$(printf "%q" "$file")
	newfile=$(printf "%q" "${names[index]}")
	eval "mv $file $newfile"
  	((++index))
done
This entry was posted in Mac, Work and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *