0

I have a directory with 400 sub-directories each containing several hundred files many with filenames that contain spaces. I need to copy all of the files with spaces in the filenames, resulting two copies of those files, one with spaces and one with underscores replacing the spaces. I see a lot of code that comes close, but nothing that will copy, rename and replace spaces recursively. Any suggestions ??? Thanks....RW Linux rename using parameters and spaces? Linux rename using parameters and spaces?

1

And yet it is not too difficult:

 for i in "$(find . -type f -name '* *' -print)"; do cp "$i" $(echo $i | sed 's/ /_/g'); done

This assumes your directory names do not contain spaces. If they do, the following bash script will work:

  #!/bin/bash

 TGT=/path/to/targt/directory
 LIST="$(find $TGT -type f -name '* *' -print)"
 for i in $LIST; do 
      dirpath=${i%/*}
      base=base=${i##*/}
      newbase=$(echo "base" | sed 's/ /_/g')
      cp "$i" $dirpath/$newbase
 done

If your directory names contain spaces, and you want those dulicated, you will have to specify better what you want to duplicate: the original files and the new ones, only the new ones, possible other files without spaces...

  • Thanks.... The directory names do not contain spaces. – user2693196 Nov 21 '13 at 6:24
  • @user2693196 if it works, you should accept my answer, so that users with similar problems searching for a solution may find it and be encouraged to use it.This both yields a faster response, and prevents a new useless post from being submitted. – MariusMatutiae Nov 22 '13 at 6:51

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.