Skip to content

Instantly share code, notes, and snippets.

@KrashLeviathan
Created January 30, 2018 01:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KrashLeviathan/023752b6d3a36e7b1cc695a134743229 to your computer and use it in GitHub Desktop.
Save KrashLeviathan/023752b6d3a36e7b1cc695a134743229 to your computer and use it in GitHub Desktop.
Rename batches of files
#!/bin/bash
function usage() {
echo "USAGE: batchrename.sh <query> <replacement> [shouldMove]"
echo -e "\n\
Rename a batch of files. The first parameter (query) should be a\n\
string common to all the filenames in the batch. The second\n\
parameter (replacement) should be a string that replaces the\n\
query in the new filenames. The third parameter indicates whether\n\
it should copy or move the files. It defaults to false.\n\
\n\
EXAMPLE: batchrename.sh 'IMG_' 'Family_Vacation_2018_' true\n"
}
query=$1
replacement=$2
shouldMove=$3
# If either of the first two parameters are empty
if [[ -z "${1// }" || -z "${2// }" ]]; then
usage
exit 1
fi
# shouldMove defaults to false
if [ -z "$3" ]; then
shouldMove=false
fi
# If there exists a file that matches the pattern...
if [ -f *"${query}"* ]; then
for filename in *"${query}"*; do
newFilename=$(echo $filename | sed "s/${query}/${replacement}/")
if $shouldMove; then
echo "mv ${filename} ${newFilename}"
mv "${filename}" "${newFilename}"
else
echo "cp ${filename} ${newFilename}"
cp "${filename}" "${newFilename}"
fi
done;
else
echo "No files found matching pattern *${query}*"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment