How to copy only the regular files in a directory (ignoring sub-directories and links) to the same destination? (bash on Linux) A very large number of files
-
4How is this off topic? I really hate this part of stackoverflow.steinybot– steinybot2019-03-17 18:56:28 +00:00Commented Mar 17, 2019 at 18:56
-
I suspect the rational is that this should go to something like Super User, which I kind of understand, but also this is a legit bash programming question.Azuaron– Azuaron2019-03-21 14:26:06 +00:00Commented Mar 21, 2019 at 14:26
-
can you rephrase the headline...this is how to copy, not how to listTim Boland– Tim Boland2019-09-11 17:24:51 +00:00Commented Sep 11, 2019 at 17:24
Add a comment
|
3 Answers
for file in /source/directory/*
do
if [[ -f $file ]]; then
#copy stuff ....
fi
done
3 Comments
glenn jackman
It also won't respect files with whitespace in the name.
mklement0
@holygeek: No, globbing (pathname expansion) is not subject to the
ARG_MAX max. command-line length limitation, because there is no external utility involved. That said, any loop with a large number of iterations in Bash will be slow.mklement0
@glennjackman: Filenames with whitespace are handled correctly, due to use of
[[ ... ]] rather than [ ... ]; [[ ... ]] doesn't require double-quoting variable references (in most cases).To list regular files in /my/sourcedir/, not looking recursively in subdirs:
find /my/sourcedir/ -type f -maxdepth 1
To copy these files to /my/destination/:
find /my/sourcedir/ -type f -maxdepth 1 -exec cp {} /my/destination/ \;
1 Comment
Anum Sheraz
Thanks :). I'd to add * to get list of all files inside sourcedir.
find /data/* -maxdepth 2 -type fTo expand on poplitea's answer, you don't have to exec cp for each file: use xargs to copy multiple files at a time:
find /my/sourcedir -maxdepth 1 -type f -print0 | xargs -0 cp -t /my/destination
or
find /my/sourcedir -maxdepth 1 -type f -exec cp -t /my/destination '{}' +
1 Comment
mklement0
-exec ... + is the most efficient solution; one thing worth mentioning: cp -t is a GNU extension.