ranger-users
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Ranger-users] Bulk renaming command


From: Roman Z.
Subject: [Ranger-users] Bulk renaming command
Date: Sat, 25 Sep 2010 13:05:06 +0200
User-agent: Mutt/1.5.20 (2009-06-14)

Here is a command for bulk-renaming, demonstrating what you can do with
a little python knowledge. It works like this:
1. A list of selected files is opened in vim
2. You can change each filename to what you want it to rename to.
   When you're done, save & close the file.
3. A shell script is generated which applies your changes.
   It will be opened in vim too.
4. Review this script and make sure this is what you want to do,
   then save & close it.
5. The script will be executed and you're back in ranger.

You can put this in ~/.config/ranger/commands.py.
Select some files (with space) and type :bulkrename to test it.


from ranger.api.commands import Command
class bulkrename(Command):
  """
  :bulkrename

  This command opens a list of selected files in an external editor.
  After you edit and save the file, it will generate a shell script
  which does bulk renaming according to the changes you did in the file.

  This shell script is opened in an editor for you to review.
  After you close it, it will be executed.
  """
  def execute(self):
    import tempfile
    from ranger.ext.shell_escape import shell_escape as esc

    # Create and edit the file list
    filenames = [f.basename for f in self.fm.env.get_selection()]
    listfile = tempfile.NamedTemporaryFile()
    listfile.write("\n".join(filenames))
    listfile.flush()
    self.fm.run(['vim', listfile.name])
    listfile.seek(0)
    new_filenames = listfile.read().split("\n")
    listfile.close()
    if all(a == b for a, b in zip(filenames, new_filenames)):
      self.fm.notify("No renaming to be done!")
      return

    # Generate and execute script
    cmdfile = tempfile.NamedTemporaryFile()
    cmdfile.write("# This file will be executed when you close the editor.\n")
    cmdfile.write("# Please double-check everything, clear the file to 
abort.\n")
    cmdfile.write("\n".join("mv -vi " + esc(old) + " " + esc(new) \
        for old, new in zip(filenames, new_filenames) if old != new))
    cmdfile.flush()
    self.fm.run(['vim', cmdfile.name])
    self.fm.run(['/bin/sh', cmdfile.name], flags='w')
    cmdfile.close()




reply via email to

[Prev in Thread] Current Thread [Next in Thread]