Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move a given number of random files on Unix/Linux OS

Tags:

linux

unix

mv

I'm facing this simple task but, I'm also wondering about what's the easiest and short way to do it.

My proposal is move a given numer of random files from a directory to another. This task is part of the creation of two datasets I need for machine learning: a training set and a testing set. My goal is move away 10% of the file from a directory in order to get the datasat agaist which I could test my categorizer, and obtain a training set from the source directory.

So, what's the most compact typing for this "move n random files" task?

Thanks in advance - as usual -

like image 454
Max Avatar asked Dec 25 '12 18:12

Max


People also ask

How do I move a random file in Linux?

So shuf -n 1 -e [PATH to the files to be moved]/* | xargs -i mv {} [PATH to the dest] would pick one random file from [PATH to the files to be moved] and move it to [PATH to the dest] (that would miss hidden files though.

How do I move a bunch of files in Linux?

Move Multiple Files With the mv Command in LinuxAfter the mv command, type the filenames you want to move and then the directory name. The use of a slash ( / ) after the directory name is optional.

How do I move bulk files in UNIX?

How to move multiple files into a directory. To move multiple files using the mv command pass the names of the files or a pattern followed by the destination. The following example is the same as above but uses pattern matching to move all files with a . txt extension.


3 Answers

Use a combination of shuf and xargs (it's a good idea to look at their documentation with man):

shuf -n 10 -e * | xargs -i mv {} path-to-new-folder 

The command above selects 10 random files of the current folder (the * part) and then move them to the new folder.

Update

Although longer, one might find this version even simpler to understand:

ls | shuf -n 10 | xargs -i mv {} path-to-new-folder 

shuf just generates a random permutation of the standard input, limiting the results to 10 (like using head, but probably faster).

like image 133
boechat107 Avatar answered Oct 06 '22 23:10

boechat107


You could use bash random generator that generates an int between 0 and 32767 to choose if a file must be put in set1 or set2. That would do:

for file in ./*; do
  val=$RANDOM
  if test $val -gt 3276; then
    mv "$file" ../set1
  else
    mv "$file" ../set2
  fi
done
like image 32
jfg956 Avatar answered Oct 06 '22 23:10

jfg956


Alternative version with find to avoid problems with folders. It copies 31415 randomly chosen files into /home/user/dir/

find . -maxdepth 1 -type f | sort -R | head -31415 | xargs cp -t /home/user/dir/
like image 30
packmad Avatar answered Oct 07 '22 00:10

packmad