简体   繁体   中英

Copy all files in folder to another folder prepending a . to the file name and rename it back to original file name

after searching and trying various way I couldn't get it work.

I need to copy lots of files (more than 100 thousand files) to another folder with dot prepended to the file name Example:

/foo/bar/filename1.txt to /foo2/bar/.filename1.txt

and then rename it back to original name /foo2/bar/filename.txt

Why I need to do this is because I have an application that will keep scanning /foo2/bar folder and its sub folder and ignore those file with a dot in front of the file name so that it will not process those file that are copying half way. This mainly because the 2 folder can be in 2 different network drive or some mounted devices.

And i cannot simply use mv or cp because I have some folder that has too many files and it will simply throw argument list too long error thus I have been trying to use find command but to no avail.

Trying out with different command:

find /foo/bar/ -type f -exec cp -t /foo2/bar {} +

and

find /foo/bar/ -type f -exec mv {} /foo2/bar/.{} \;

I know the above command won't do what I wanted but that is along the line of what i've tired.

Appreciate anyone that can help...

Let's suppose we have two directories as follows:

$ ls -a foo*
foo1:
 .   ..   file1   file2   file3  'file 4'

foo2:
.  ..

If we execute next command:

$ for file in foo1/* ; do base=$(basename "$file"); cp "foo1/$base" "foo2/.$base"; mv "foo2/.$base" "foo2/$base"; done

We will get at the end:

$ ls -a foo*
foo1:
.  ..   file1   file2   file3  'file 4'

foo2:
.   ..   file1   file2   file3  'file 4'

I think this is what you wanted.

Moreover, the file names with spaces inside will be correctly handled.

Copy all files to new dir with the new name:

for file in *; do   cp "$file" "./files2//.${file}"; done

$ ls -la ./files2/
total 4
 .
 ..
 .1
 .2
 .3

Rename files:

cd files2
rename . "" .*

output:

$ ls -la 
total 4
 .
 ..
 1
 2
 3

Would you try the following:

src="/foo/bar"
dest=/foo2/bar"
while IFS= read -r -d "" f; do
    cp -p -- "$src/$f" "$dest/.$f"
    mv -- "$dest/.$f" "$dest/$f"
done < <(find "$src" -type f -printf "%f\0")

-printf "%f\\0" is mostly similar to -print0 except it strips off the directory name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM