Bash snippet to move all files in a directory into that directory

I have a directory with lots of files and directories in it. In order to tidy it up, I'm going to put all those files into a directory, so I was going to do something like this:

$ ls | wc -l
123
$ mkdir new_directory
$ mv * ./new_directory

However that obviously won't work because then it'll try to move new_directory into new_directory. Is there some simple way to do what I want in one line without me having to copy and paste all the files and directories in that directory?


Solution 1:

Your

mv * ./new_directory
command will actually work; it'll just print a warning that it can't move that directory into itself.

Solution 2:

A fast and dirty oneliner.

mv `ls -A | grep -v new_directory` ./new_directory

Solution 3:

If you're just looking for the files (i.e. not directories), then

find . -type f -maxdepth 1 -exec mv {} ./new_directory/ \;

is the most portable solution. For speed, you should move find and xargs, with -print0 and -0, but only if you've got GNU find and xargs.

Solution 4:

The times that I've had this problem, I've done one of the following:

$ mkdir ../new-directory
$ mv * ../new-directory/
$ mv ../new-directory .

or

$ mkdir .new-directory
$ mv * .new-directory/
$ mv .new-directory new-directory

The second form takes advantage of the wildcard skipping filenames that start with '.'