Portál AbcLinuxu, 20. prosince 2025 09:20
#!/usr/bin/python
import gtk, sys, os, glob, re
f = ['*']
cd = os.path.realpath(os.curdir) + '/'
def delprefix(x):
if x.startswith(cd):
return x[len(cd):]
return x
def select_files(*args):
global f, files
selector = gtk.FileSelection('Select files')
selector.set_select_multiple(True)
selector.run()
f = [delprefix(x) for x in selector.get_selections()]
print f
selector.destroy()
files.set_text(' '.join(f))
def slabel(text, table, row, widget):
label = gtk.Label()
label.set_text_with_mnemonic(text)
label.set_alignment(0, 0.5)
label.set_mnemonic_widget(widget)
table.attach(label, 0, 1, row, row+1)
dialog = gtk.Dialog('Search & Replace', None, 0,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
dialog.set_border_width(8)
table = gtk.Table(6, 3, False)
table.set_row_spacings(4)
table.set_col_spacings(4)
dialog.vbox.pack_start(table)
dialog.vbox.set_spacing(4)
search = gtk.Entry()
slabel('_Search for', table, 0, search)
table.attach(search, 1, 2, 0, 1)
replace = gtk.Entry()
slabel('_Replace with', table, 1, replace)
table.attach(replace, 1, 2, 1, 2)
files = gtk.Entry()
slabel('In _files', table, 2, files)
files.set_text(' '.join(f))
table.attach(files, 1, 2, 2, 3)
browse = gtk.Button('_Browse...')
table.attach(browse, 2, 3, 2, 3)
browse.connect('clicked', select_files)
recursive = gtk.CheckButton('Recurse into sub_directories')
table.attach(recursive, 0, 2, 3, 4)
globally = gtk.CheckButton('Replace _all occurences')
table.attach(globally, 0, 2, 4, 5)
ignorecase = gtk.CheckButton('_Ignore case')
table.attach(ignorecase, 0, 2, 5, 6)
table.show_all()
response = dialog.run()
f = files.get_text().split(' ')
f = reduce(lambda x, y: x+y, [glob.glob(x) for x in f])
search = search.get_text().replace('/', '\\/')
replace = replace.get_text().replace('/', '\\/')
if (response == gtk.RESPONSE_CANCEL
or response == gtk.RESPONSE_DELETE_EVENT
or not f or not search):
sys.exit(0)
recursive = recursive.get_active()
ignorecase = ('', 'i')[ignorecase.get_active()]
globally = ('', 'g')[globally.get_active()]
dialog.destroy()
ff = []
for x in f:
if os.path.isdir(x):
if recursive:
p = os.popen('find ' + re.sub(r'([$`"\\])', r'\\\1', x)
+ ' -type f', 'r')
ff.extend([z.strip() for z in p.readlines()])
p.close()
else:
ff.append(x)
ff = dict([(x, 1) for x in ff]).keys()
exp = 's/%s/%s/%s%s' % (search, replace, globally, ignorecase)
if ff:
os.execv('/bin/sed', ['sed', '-i', '-e', exp, '--'] + ff)
Tiskni
Sdílej:
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.