Skip to content

Instantly share code, notes, and snippets.

@wenlibin02
Created October 16, 2017 03:01
Show Gist options
  • Save wenlibin02/662eb7841e3c8d7bc7ae3757788fe0d3 to your computer and use it in GitHub Desktop.
Save wenlibin02/662eb7841e3c8d7bc7ae3757788fe0d3 to your computer and use it in GitHub Desktop.
A bash script for editing multiple file/dir names using a text editor (e.g. vim). Usage: edit_filename.sh file1 file2 ...
#!/usr/bin/env bash
tmpfile0="$(mktemp -t ename0_XXXXXXXX)"
tmpfile1="$(mktemp -t ename1_XXXXXXXX)"
myeditor=vim
for i in "$@"; do
if [ ! -f "$i" ]; then
echo "file $i does not exist ... exit ... "
exit 1
fi
echo "$i" >> "$tmpfile0"
echo "$i" >> "$tmpfile1"
done
md5sum_orig="$(md5sum "$tmpfile1" | awk '{print $1}')"
$myeditor "$tmpfile1"
md5sum_new="$(md5sum "$tmpfile1" | awk '{print $1}')"
if [ "$md5sum_new" == "$md5sum_orig" ]; then
echo 'filenames unchanged, exit ... '
exit 0
fi
n=1
for i in "$@"; do
newname_i="$(sed -n "${n}p" "$tmpfile1")"
if [ "$newname_i" == "${i}" ] || ! echo "$newname_i" | sed 's/\s*//g' | grep -q '.'; then
echo -e "\033[33;5mUNCHANGED\033[33;0m: ${i}"
echo
let n+=1
continue
fi
echo -e "\033[33;1mRENAMING\033[33;0m: ${i} "
echo " ===>> ${newname_i}"
echo
mv "${i}" "${newname_i}"
let n+=1
done
if [ -f "$tmpfile0" ]; then
rm "$tmpfile0"
fi
if [ -f "$tmpfile1" ]; then
rm "$tmpfile1"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment