truncate file names (using perl's rename)

Cameron Hutchison camh+ubuntu at
Wed May 11 06:08:43 UTC 2005

Once upon a time toyfactory said...
> I'm sorry if this is not Ubuntu specific but...
> I'm trying to figure out an easy way to truncate filenames to a specific
> length while retaining the extension.  [...] In
> the meantime I discovered there's a rename command included with Perl.
> Can anyone save me an afternoon of unproductive Googling and head
> scratching and just tell me how to do it?  For example:
> using 'rename <complicated regex here> *.txt'
> 'this_filename_is_simply_too_long_for_my_liking.txt'
> becomes
> 'this_filename.txt'

My perl regexes are a but rusty, but this seems to work:

rename 's/(.{4}).*(\.[^\.]*)/$1$2/' *.txt

The {4} contains the length of the filename before the extension you
want. The part of the filename after the last dot is considered the
extension. ie. if you truncate 1234.5678.txt to four chars, you get

More information about the ubuntu-users mailing list