Simple and short question; is it possible for mv to move a random file?

I know mv can move all files with a specific extension using mv *.extension, but as I'm pretty new to Ubuntu/Linux overall I'm unsure whether mv can do this or not.


Take a look at the man pages for the shuf and xargs commands, this might be what you are looking for:

shuf -n [Number of files to move] -e [PATH to the files to be moved] | xargs -i mv {} [PATH to the dest]
  • 1
    Right, but I think you want [PATH to the files to be moved]/* – kos Mar 31 '16 at 22:19
  • Thank you both. It works perfectly. Is it possible to rename the file that gets moved? – realsub Mar 31 '16 at 22:22
  • Well, it depends on [Number of files to move] (by the way the question asks for how to move a single file). 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. To include also hidden files: shopt -s dotglob; shuf -n 1 -e [PATH to the files to be moved]/* | xargs -i mv {} [PATH to the dest]). – kos Mar 31 '16 at 22:23
  • I see. I'm currently trying to move one random picture to a folder and change the picture name, and then have it moved back to the picture's folder upon my next reboot with some random name, so there aren't any issues with duplicate filenames. – realsub Mar 31 '16 at 22:35

Here's a shell-only approach:

## Save all files in the array $files
## Get a random number between 0 (arrays start counting at 0) and the 
## the number of files -1 (the last file in the array)
until (( $rand < ${#files[@]} && $rand >= 0 )); do rand=$RANDOM; done
## Move the file, renaming as necessary
mv "${files[$rand]}" newfilename

You can copy/paste the above directly into your terminal.

Alternatively, in Perl:

perl -le 'rename $ARGV[int(rand($#ARGV))],newfilename' *

The rename function simply renames its first argument as its second: rename orifinal_file new_file. The rand function prints a random fractional number between 0 and the argument given. $#ARGV is the number of arguments given to the script, here, all files (and subdirectories) in the current directory. Since rand returns fractional numbers, we pass it through int() to get an integer. So, int(rand($#ARGV)) picks one of the indices in the @ARGS array randomly and therefore $ARGV[int(rand($#ARGV))] is one of the files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.