Ubuntu – Remove Leading or Trailing Space(s) in File or Folder Names


I worked out a neat way ro get rid of duplicate files. You know, the ones that contain "(1).", "(2).", "(3).", etc. in their names. In a terminal window, at the command line, you type in "rm "[backslash]").", but without the quotes. That will do it. The [backslash] "\" means the next character is accepted as just a character, not part of a pair of parentheses. This works when nothing else will. Incidently, I tried to type the "\" into the "rm" command, but it failed to display properly, so I put the term [backslash] there instead.

The appearance of "\ " in a folder or a filename shows the presence of a space there as well. The use of spaces in names is not all that common, unless you work with Windows. Windows just has you bracket the "whole path\file name" in double quotes. You can do that in Ubuntu as well, or just stick a backslash "\" in front of the space. But what if you want to replace the space with a different character instead? Like a hyphen or underscore? How would you do that for all folders and files at once?

Or what if you decide to just remove the spaces, just pack the rest of the characters together? How would you do that?

And here is a toughy: Just get rid or any leading or trailing spaces. even if there is more than one present.

And to wrap it up, how to detect and delete and files that are completely empty. Or folders that are empty.

Best Answer

  • To remove any number of leading spaces from file names you can use rename (prename) :

    rename -n 's/^ *//' *
  • To remove any number of trailing spaces from file names you can use rename (prename) :

    rename -n 's/ *$//' *

    Remove -n (dry-run) if you are satisfied with the file names.

  • To remove files or folders that are empty (recursively) :

    find . -empty

    Satisfied ? Let the action take place :

    find . -empty -delete

    Only in the current directory :

    find . -maxdepth 1 -empty -delete

    Also use -type f for only files and -type d for only directories if you want.

Read man rename and man find to get more idea.