Open dotsdl opened 5 years ago
Do we really need to ship a rename
alias? There are cross-platform implementations out there, e.g. brename. Perhaps a xontrib might be more appropriate?
Any how, what about wrapping re.sub
, keeping things simple yet familiar to Pythonistas:
import os
import re
def _srename(args, stdin=None):
pattern, repl, files, options = _parse_srename_args(args)
if options['invert']:
pattern, repl = repl, pattern
for old_name in files:
if not os.path.exists(old_name):
print(f'Warning: {old_name} does not exist')
continue
new_name = re.sub(pattern, repl, old_name)
if (old_name == new_name):
continue
if os.path.exists(new_name):
print(f'Warning: {new_name} already exists')
continue
if options['dry-run']:
print(f'Info: {old_name} → {new_name} (not renaming as dry run)')
else:
os.rename(old_name, new_name)
def _parse_srename_args(args):
options = {'dry-run': False, 'invert': False}
if '--dry-run' in args:
args.remove('--dry-run')
options['dry-run'] = True
if '--invert' in args:
args.remove('--invert')
options['invert'] = True
pattern, repl, *rest = args
return pattern, repl, rest, options
aliases['srename'] = _srename
e.g.
touch foo1.txt foo2.txt
srename foo bar *.txt
srename foo bar *.txt --invert
srename foo @(lambda match: f'{match.group(0).upper()}BAR') *.txt
Initial xontrib draft, comments welcome.
This would be great to have in xoreutils
!
Reference xonsh/xonsh#308
Create a
rename
alias that works across platforms. This is currently unavailable on e.g. MacOS.For community
⬇️ Please click the 👍 reaction instead of leaving a
+1
or 👍 comment