‹ back home

Editing filenames and directories in Vim

2024-07-02 #open-source #tools

I have a list with ideas of “useful tools that I want to write someday” that would likely take hundreds of years to complete. Finding out that somebody has already written one the tools in this list pleases me immensely, not only because I can use the tool in this lifetime, but actually right now!

Today I came across vidir, from the moreutils package. It lets me edit a filenames and directories in Vim.

The idea is pretty simple; when I want to edit the filenames inside a directory, I run vidir path/to/directory/. This opens my text editor1 with a temporary file where each line contains a number and a filename. I can edit filenames, exit Vim, and vidir will rename these files to match my changes. Deleting lines deletes the corresponding files.

Here’s an example (when using vidir photos/Unsorted/:

0001	photos/20120718_002.jpg
0002	photos/IMG_0021.JPEG
0003	photos/IMG_0166.JPEG
0004	photos/IMG_0191.JPEG
0005	photos/IMG_1168.JPEG
0006	photos/IMG_1170.JPEG
0007	photos/IMG_1465.JPEG
0008	photos/IMG_1796.JPEG
0009	photos/IMG_1802.JPEG
0010	photos/IMG_1902.JPEG
0011	photos/IMG_2032.JPG
[...]

I can quickly replace all instances of \.JPEG$ and \.jpg$ with .jpeg using Vim’s replacement command2. Once I exit Vim, vidir will rename all these files at once. If I give multiple files the same name, one of them will include a trailing ~, the next one a trailing ~1, and so forth. This prevents unintentionally overwriting files.

The numbers at the beginning of each line are used internally by vidir to match which line corresponds to which original file.

My own idea was pretty similar, but for some reason I had planned on using inode numbers instead of sequential numbers. I now see that it the design could be much simpler.

Update 2024-07-02

vidir can also handle files in multiple directories or an entire tree of files. For example:

fd -t d  | xargs vidir  # all files in current directory tree
fd 'py$' | xargs vidir  # all python files in the current directory tree

  1. neovim in my case, but this can be controlled by setting the $EDITOR environment variable. ↩︎

  2. This isn’t a great example: this task can easily be done with a script. I wish I could remember more interesting use-cases for which I’ve needed this tool, but my notes on this don’t elaborate further. ↩︎

Have comments or want to discuss this topic?
Send an email to my public inbox: ~whynothugo/public-inbox@lists.sr.ht.
Or feel free to reply privately by email: hugo@whynothugo.nl.

— § —