linux - Recursively copy and rename to replace spaces with underscore
2014-04
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?
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...
Is it possible, in Linux, to rename a file from something without spaces to something containing spaces?
I know I can create directories and files with spaces by doing:
mkdir "new dir"
and:
touch "new file.txt"
I want to rename files from:
imgp0882.jpg
to something like:
20091231 1243 some topic.jpg
And how would it look in a shell script that uses parameters like:
for i in *.jpg do
rename "$i" "$somepath/$mydate $mytime $mytopic$extension"
?
A little background:
- I'm new to Linux (using PCLinuxOS 2009.2), coming from Windows, and I've written myself a little shell script to download files from my camera and then automatically rename them according to a date-and-topic pattern. As you can guess by now, I'm stuck on the bit about renaming.
- If you want to see my script, here's a copy.
- I'm not using
jhead
for this renaming because that only works with JPEG files but I want a single solution for any media format including videos.
Maybe you need to just put quotes around whole destination path? E.g.
$ touch test
$ a=one
$ b=two
$ mv "test" "$a $b"
$ ls -la
total 8
-rw-r--r-- 1 whitequark whitequark 0 2010-01-27 01:21
-rw-r--r-- 1 whitequark whitequark 0 2010-01-27 01:20
drwxr-xr-x 2 whitequark whitequark 4096 2010-01-27 01:21 .
drwxr-xr-x 80 whitequark whitequark 4096 2010-01-27 01:16 ..
-rw-r--r-- 1 whitequark whitequark 0 2010-01-27 01:21 one two
If you're using bash, backslash-escape your spaces:
My\ File\ Name.jpg