Home > front end >  macos rename all files by keeping the last n characters
macos rename all files by keeping the last n characters

Time:12-11

How would I recursively rename

filename9_123.txt
filename10_124.txt
filename11_125.txt

to

123.txt
124.txt
125.txt

CodePudding user response:

Can I use ruby? Should work with the version installed by default. NOTE: will overwrite files if the names clash.

 ruby -e "require 'pathname';Pathname.glob('*_*.txt')
    .each {|f| f.rename f.basename.to_s.split('_').last }"

You may need to remove the linebreak, that's just for better formatting here.

If by "recursively" you mean in subdirectories:

ruby -e "require 'pathname';Pathname.glob('**/*_*.txt')
    .each {|f| f.rename(f.dirname / f.basename.to_s.split('_').last) }"

This version fails it it's about to overwrite an existing file:

 ruby -e "require 'pathname';Pathname.glob('**/*_*.txt')
    .to_h {|f| [f, f.dirname / f.basename.to_s.split('_').last] }
    .each {|from, to| fail(to) if to.exists?; from.rename to }"
  • Related