2

There is an answer that is very useful to me in this thread about renaming folders with trailing whitespaces: Remove Leading or Trailing Space(s) in File or Folder Names

What I can't figure out how I can change the following command so that it also changes the names in subfolders.

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

I obviously already tried to check this myself with "rename -h" but I can;t see the solution.

Can someone help me with this?

Thanks a lot in advance,

Chris

3 Answers3

5

If your subfolders as well as files may end with trailing spaces (as discussed in comments), then you will need to process the directory tree depth first1. You can do this with the find command:

find . -depth -name '* ' -execdir rename -n 's/ *$//' {} +

You can replace . (current directory) with a specific starting directory path/to/dir.

The use of -execdir rather than -exec ensures that the replacement is only applied to the file or directory name (rather than the whole path), so it's safe even when the regex pattern isn't anchored to the filename.


1. otherwise it will look OK when testing with -n but will likely fail when applied for real, since it will attempt to rename files in directories whose names have already been changed

steeldriver
  • 142,475
4

You may just need to enable the globstar option of the bash shell then use **/* instead of *:

shopt -s globstar
rename -n 's/ *$//' **/*
  • where -n option is dry run.
pa4080
  • 30,621
1

First, let's look at your use of the rename command. I changed it to match trailing spaces for files with or without an extension:

rename -n 's/( +?)(?=\.[^.]*$|$)//' *

Then to act on all files and files in subfolders, you can use the find command to find all files or directories in a certain path

find . -type f 
find . -type d

and use the -exec subcommand of find to operate on those files or directories. Place the rename command after the exec subcommand. For example:

find . -type f -exec rename -n 's/( +)(?=\.[^.]*$|$)//' {} +
pm-b
  • 154