Copy first n files in a different directory

Possible Duplicate:
How to move 100 files from a folder containing thousands?

Is it possible to copy only the first 1000 files from a directory to another?

Thanks in advance

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The following copies the first 1000 files found in the current directory to $destdir. Though the actual files depend on the output returned by find.

$ find . -maxdepth 1 -type f |head -1000|xargs cp -t "$destdir"

You’ll need the GNU implementation of cp for -t, a GNU-compatible find for -maxdepth. Also note that it assumes that file paths don’t contain blanks, newline, quotes or backslashes (or invalid characters or are longer than 255 bytes with some xargs implementations).

EDIT: To handle file names with spaces, newlines, quotes etc, you may want to use null-terminated lines (assuming a version of head that has the -z option):

find . -maxdepth 1 -type f -print0 | head -z -n 1000 | xargs -0 -r -- cp -t "$destdir" --

Method 2

A pure shell solution (which calls cp several times).

N=1000;
for i in "${srcdir}"/*; do
  [ "$((N--))" = 0 ] && break
  cp -t "${dstdir}" -- "$i"
done

This copies a maximum number of $N files from $srcdir to $dstdir. Files starting with a dot are omitted. (And as far as I know there’s no guaranty that the set of chosen files would even be deterministic.)

Method 3

The following scary 1-liner:

perl -MFile::Copy -e 'opendir(DIR,$ARGV[0]);$n=1000; (-f $_) && copy($_,"$ARGV[1]/$_") while($n-- && readdir(DIR))

works for file containing spaces, quotes, etc., which tend to break shell-based solutions (short of $IFS contortions). ‘Course if your file names are behaved, shell is fine.

Edit: added check for copying only files.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x