i have a directory full of sub-directories with names like

  • 01 - title of folder
  • 02 - second title
  • 03 - etc
  • 04 - etc . . .
  • 30 - final folder

i want to truncate all of these folder names to just be the numbers so they would appear like so:

  • 01
  • 02
  • 03

is there a way to write a script or a simple command that will accomplish this?


Using the Perl-based rename utility (which appears to be what Ubuntu provides), you could do the renaming operation like this (replacing * with whichever list of directories you actually want):

rename 's/^(\S+).*/$1/' *

(I suggest using rename -n at first to see what would be done before actually renaming anything.)

The replacement string asks to match a sequence of non-space characters (\S+) at the start (^) of the original file name, followed by anything (.*), and replacing it with the first matched group ($1), which was the initial space-free segment.

  • this worked perfectly thanks! is there a document somewhere that shows all the string commands? the ^(\S+) etc – kitties heart Feb 3 '17 at 22:12
  • The syntax used by this version of the rename command is that of Perl regular expressions; you can access its documentation using man perlre if installed on your system, or e.g. at perldoc.perl.org/perlre.html – dhag Feb 4 '17 at 5:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.