1

Pretty new to Linux, but have discovered the 'dislike' Linux have for spaces in names.

By using :rename 's/ /_/g' * it renames everything in that directory by adding a _underscore instead of the spaces. So "test dir nr 1 becomes "test_dir_nr_1" and "test file 1.txt" becomes "test_file_1.txt"

But! Is there anyway to make it automated and recursive (is that the right word?, ) doing subdirectories in subdirectories as well?

1 Answer 1

1

With GNU find:

find . -name "* *" \( -type f -o -type d \) -execdir rename -v 's/ /_/g' {} +

This searches for regular files and directories containing a space character in their names using your current directory (.) as start directory and renames them recursively. I just added the -verbose flag so you can see what happens.

To list the files and directories which would be affected by the command, remove the -execdir part:

find . -name "* *" \( -type f -o -type d \)

You can of course replace the . with an absolute or relative path.

2
  • Wow, that string was pretty impressive, it did it all, I expected a 10 page script ☺️ I'm still learning, so what does the last {} + do?
    – JoBe
    Commented Feb 9, 2020 at 14:10
  • The {} is a placeholder and expands to the list of pathnames found by find, i.e. the rename command is executed on this list. The + is used to execute the command for as many matching pathnames as possible. There exists another variant with a semicolon ; which would execute the command once for each file which results in multiple calls of the command and is slower. See -execdir command {} + and -execdir command ;.
    – Freddy
    Commented Feb 9, 2020 at 14:31

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