Welcome, guest | Sign In | My Account | Store | Cart

Rename (move) a file with help of GNU Readline library.

Python, 39 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/python

import readline
import shutil
import sys
import os


def main():
    """
    interactive move of a file. Instead of calling mv with two
    arguments, source and destination, call imv with just the source,
    and edit the destination in a GNU readline buffer.

    Once the line editor is started, it is possible to cancel with
    Ctrl-C without harming the filesystem.
    """
    if (sys.argv[1] == '-h' or sys.argv[1] == '--help'):
        help(main)
        sys.exit(0)
    else:
        for src in sys.argv[1:]:
            if os.path.exists(src):
                def pre_input_hook():
                    readline.insert_text(src)
                    readline.redisplay()
                readline.set_pre_input_hook(pre_input_hook)
                try:
                    dst = raw_input('imv$ ')
                except KeyboardInterrupt:   # die silently if user hits Ctrl-C
                    pass
                else:
                    shutil.move(src, dst)
            else:
                print 'ERROR: %s: no such file or directory' % src
                sys.exit(-1)

if __name__ == "__main__":
    main()

The Unix 'mv' command takes two arguments: source and destination. Sometimes, the destination only modifies a few characters. Instead of typing two file names, just do an imv RET, then edit the buffer, type RET again, and voila!

The script will do as many renames as there are arguments on the command line.

I use it a lot to add a suffix, like .bak, .old, .orig, etc.