Useful Shell Scripting and Bulk Renaming Files with Vim

I used to use vifm, a terminal file manager, on FreeBSD and Linux. I realized the only feature I was really using was bulk interactive file renaming with vim. So I ditched the file manager altogether and implemented the bulk rename feature in a few lines of shell.

Lots of terminal file managers have this feature (lf, vifm, ranger), and I tried a bunch but always ended up going back to just cd-ing around in the terminal and opening files most of the time. The only feature that did keep me using file managers/browsers/explorers was the bulk rename. For example, in vifm, you can select a bunch of files and open all of their names in a Vim buffer, one per line. You make a bunch of bulk changes or one-offs, and then save and quit. All of the files get renamed to whatever their line changed to. Since this was the only feature I was using I decided to implement it myself with just a little useful shell scripting.


rename() {
	src="$(mktemp -t rename)" # Make a temp file for source filenames
	dst="$(mktemp -t rename)" # Make a temp file for destination filenames
	printf '%s\n' "$@" | tee "$src" > "$dst" # Write args (filenames) into temp files
	$EDITOR "$dst" # Edit the destination filenames
	diff -s "$src" "$dst" > /dev/null || paste "$src" "$dst" | sed -e "s/\t/' '/" -e "s/^/mv -i '/" -e "s/$/'/" | sh 
		# Change the source filenames into destination filenames by rewriting as mv commands
}

Here's the function! That's all there is to it. It reads in a list of filenames from the args and writes them all to two temporary files. It then opens an editor and lets you interactively rename files (by hand, with regexes, macros, etc.). Then you save and quit your editor and (as long as the old and new names are different), generates mv commands to rename everything. It pipes those commands to a shell.

I could have alternatively read files from STDIN but I chose to use args so that I could more easily make use of shell globbing and wildcards. It makes more sense to make my rename tool take arguments the way that cp and mv do.

I've been using this renaming extensively, especially for tagging TV show DVD rips. It's so handy I just put it in my shell's startup aliases. I also uninstalled vifm, the file manager I had been using for just this purpose.