Vim Tips Wiki
(Insert TipProposed template + minor manual clean)
No edit summary
Line 34: Line 34:
 
To change all the <tt>.JPEG</tt> extensions to <tt>.jpg</tt>:
 
To change all the <tt>.JPEG</tt> extensions to <tt>.jpg</tt>:
 
<pre>
 
<pre>
:%s/JPEG/jpg/g
+
:%s/.*/mv -i & &/g
  +
:%s/.JPEG$/.jpg/g
 
</pre>
 
</pre>
   
Line 40: Line 41:
 
<pre>
 
<pre>
 
:%s/.*/mv -i & &/g
 
:%s/.*/mv -i & &/g
:%s/.jpg.jpg^/.jpg/g
+
:%s/.jpg.jpg$/.jpg/g
 
</pre>
 
</pre>
   

Revision as of 12:18, 4 February 2010

Proposed tip Please edit this page to improve it, or add your comments below (do not use the discussion page).

Please use new tips to discuss whether this page should be a permanent tip, or whether it should be merged to an existing tip.
created December 22, 2009 · complexity basic · author Whiteinge · version 7.0

You can use Vim to quickly rename many files at once. This is essentially constructing an in-memory simplistic shell script.

Read in the list of files via stdin

The backslash tells your shell to disregard any aliases for ls; we need plain output with no color.

\ls | vim -

Make stand-alone shell commands

In Vim you now have one filename per line. We need to construct each line to be a valid stand-alone shell command.

For example, to rename a bunch of files to lowercase:

:%s/.*/mv -i & \L&/g

To append .orig to each filename:

:%s/.*/mv -i & &.orig/g

To change all the .JPEG extensions to .jpg:

:%s/.*/mv -i & &/g
:%s/.JPEG$/.jpg/g

To remove duplicate extensions:

:%s/.*/mv -i & &/g
:%s/.jpg.jpg$/.jpg/g

You can use any Vim features here (macros are useful), as long as each line contains a valid shell command.

Commit your changes to disk

:w !sh

The reason this works is Vim writes a file line-by-line. So if you have a list of 100 file names, it will execute 100 mv commands. Sure there are utilities out there that may do this better or more quickly, but Vim is always available and that's one less thing you have to remember.

Comments

 TO DO 

  • Isn't the .JPEG example missing the mv stuff?
  • What is the hat doing in .jpg^ (perhaps $)?
  • Probably should generalise by adding a section for Windows.