edname/edname.sh

82 lines
1.7 KiB
Bash
Executable file

#!/bin/sh
###
# help
###
if [ "$1" = "--help" ] || [ "$1" = "-h" ] ; then
echo 'edname: rename files using $EDITOR.'
echo
echo 'usage:'
echo
echo ' edname <dir or files>'
echo ' to rename'
echo
echo ' edname --undo'
echo ' to undo the last rename (as well as possible)'
echo
exit 1
fi
###
# functions
###
execute_rename() {
command="$1"
lines="$(cat .original.edname | wc -l)"
if [ "$lines" != "$(cat .rename.edname | wc -l)" ] ; then
echo "mismatch in number of lines! not continuing. make sure no lines are added or removed!"
exit 1
fi
IFS=$'\n' read -rd '' -a src_lines < .original.edname
IFS=$'\n' read -rd '' -a dest_lines < .rename.edname
for line in $(seq 1 "$lines") ; do
src="${src_lines[$line]}"
dest="${dest_lines[$line]}"
if [ "$src" != "$dest" ] ; then
eval "$command"
fi
done
}
###
# main
###
if [ "$1" = "--undo" ] ; then
echo "undoing rename"
execute_rename "echo \"\\\"\$dest\\\" -> \\\"\$src\\\"\""
execute_rename 'mv "$dest" "$src"'
echo "done"
exit
fi
echo "-- DO NOT delete lines. This will cause files to be renamed erratically. --" > .original.edname
find "$@" -maxdepth 1 -not -path "." -not -path "*.edname" | sed -e 's/^\.\///g' | LC_COLLATE=C sort >> .original.edname
cp .original.edname .rename.edname
echo opening editor.
$EDITOR .rename.edname || exit $?
echo
echo "*** about to do the following rename:"
echo
execute_rename "echo \"\\\"\$src\\\" -> \\\"\$dest\\\"\""
echo
echo "***"
echo
echo "note: possible collisions will be ignored and Not renamed."
echo -n "confirm rename? (enter/^C) "
read
execute_rename 'mv --no-clobber "$src" "$dest"'
echo
echo "you may undo this rename using 'edname --undo'. thank you."