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 Answers1

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...

MariusMatutiae
  • 48,517
  • 12
  • 86
  • 136