Bulk Rename Files With Vim
Quick and dirty tip I found elsewhere and keep on forgetting
when I need it. When you want to bulk rename some files and want to use the
comfort of vim rather than tinkering with
First up, list the files of interest and throw the list into vim. For example, to get all the files in the folder.
ls -1 | nvim -
This result in your vim being opened with a buffer with on each line a file
from the folder you are in, i.e., the result of
You can then turn this into many
mv commands with a simple substitution. The
" are handy in case of spaces.
:%s/.*/mv "\0" "\0"/
file1 file2 file3
mv "file1" "file1" mv "file2" "file2" mv "file3" "file3"
If the bulk change you want to make is simple enough, you can just squeeze it
into that substitution. For example adding
.backup to the end of every file.
If you want to make a more involved change, my personal preference is as
follows. Record a macro for the first line. Next just use the macro on the
other lines that need changing. So for example if you recorded a macro into the
w register, then you can execute it on multiple other
:%norm! @wfor all lines,
:'<,'>norm! @wfor visual selection.
:g/pattern/norm! @wfor lines matching a pattern.
Finally, to execute all lines in the file use the magical looking
This apparently writes the lines one by one into the given command, which executes them.