Skip to content

Instantly share code, notes, and snippets.

@metacollin
Last active Feb 4, 2018
Embed
What would you like to do?
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