Skip to content

Instantly share code, notes, and snippets.

@metacollin
Last active February 4, 2018 14:22
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 metacollin/33da3627cce43d2244406d13a4a2ee34 to your computer and use it in GitHub Desktop.
Save metacollin/33da3627cce43d2244406d13a4a2ee34 to your computer and use it in GitHub Desktop.
A quick, dirty, and likely dangerous bash function to rename files using a find-replace style regex with capture groups referenced as such: \1 \2 \3...n
# source this file or copy and paste it into your ~/.bash_profile
function mv_regex()
{
regex="$1"
replace="$2"
FILE_LIST=()
NEW_NAMES=()
files="*"
for f in $files
do
if [[ $f =~ $regex ]]; then
if [[ ${#BASH_REMATCH[@]} > 1 ]]; then
let "var=0"
for i in "${BASH_REMATCH[@]}"
do
target="\\$var"
yarget="${BASH_REMATCH[$var]}"
new_name="${replace//$target/$yarget}"
let "var=var+1"
done
echo "$f --> $new_name"
FILE_LIST+=("$f")
NEW_NAMES+=("$new_name")
fi
fi
done
read -r -p "Proceed? [y/N] " response
reponse=${response,,}
if [[ "$response" =~ ^(yes|y|like a motherfucker)$ ]]; then
let "windex=0"
for i in "${FILE_LIST[@]}"
do
mv "$i" "${NEW_NAMES[$windex]}"
let "windex=windex+1"
done
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment