0

I would like to know how to move or copy specific number of files to another directory.

For example: If I have 880 files in directory A and want to move or copy 150 files from A to directory B and also 150-300 files from A to directory C.

I already tried this command

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

But this is copying 880 files to directory B

Tigger
  • 3,647

2 Answers2

0

A possible solution to mv 150 files:

mv `find ./ -maxdepth 1 -type f | head -n 150` "$destdir"

Swap out mv for cp to copy instead.

Here is a test case:

mkdir d1 d2
cd d1
touch a b c d e f g h i j k l m n o p
cd ../
mv `find ./d1 -type f | head -n 5` ./d2/

And the result:

ls d1 d2
d1:
b  c  d  e  g  h  i  k  m  n  o

d2:
a  f  j  l  p

Edit:

Here is a simple script that will answer your comment:

#!/bin/sh
# NOTE: This will ONLY WORK WITH mv.
# It will NOT work with cp.
#
# How many files to move
COUNT=150
# The dir with all the files
DIR_MASTER="/path/to/dir/with/files"
# Slave dir list - no spaces in the path or directories!!!
DIR_SLAVES="/path/to/dirB /path/to/dirC /path/to/dirD"

for d in $DIR_SLAVES
do
    echo "Moving ${COUNT} to ${d}..."
    mv `find ${DIR_MASTER} -maxdepth 1 -type f | head -n ${COUNT}` "${d}"
done

exit

NOTE: The sample script has not been tested, but should work.

Tigger
  • 3,647
  • for first 150 files will move to B dir but i need second 150 files ie (151-300) to be moved in C dir??? – Sunitha Bist Jul 01 '17 at 10:08
  • @SunithaBist See edit. I added a simple script to do that. It may be possible as a single line, but that is what I do and use. – Tigger Jul 01 '17 at 10:19
0

In case your shell supports process substitution then you could try this:

The first 150 feiles will be copied over to destdir_B and the NEXT 300 to destdir_C. Any remaining would remain untouched.

{
   head -n 150 | xargs -t cp -t "$destdir_B"
   head -n 300 | xargs -t cp -t "$destdir_C"
} <(find . -maxdepth 1 -type f)

This comes with the usual caveats of not being able to handle exotic filenames.

And when you don't have <(...) you could save find output to a file then redirect that file into the {...}

HTH