How to move all files in current folder to subfolder?

I am at the path:

/myuser/downloads/

And I create a sub folder:

/myuser/downloads/new

Now I want to move all files and folders/sub-folders in the downloads folder to the sub-folder.

how can I do this?

I tried:

mv -R *.* new/

But move doesn't take the -R switch it seems.


Solution 1:

The command

mv !(new) new

should do the trick. If it doesn't work, run shopt -s extglob first.

To also move hidden files/directories (that beginning with a dot), run also shopt -s dotglob first.
So, to sum up:

shopt -s extglob dotglob
mv !(new) new
shopt -u dotglob

(it is always better to unset dotglob to avoid bad surprises).

Solution 2:

I found something like this but is a bit simpler to understand, and it might work well for you too:

ls | grep -v new | xargs mv -t new

Adding an explanation to the above solution:

From man pages:

  • mv -t

    -t, --target-directory=DIRECTORY
          move all SOURCE arguments into DIRECTORY
    
  • grep -v

    -v, --invert-match
          Invert the sense of matching, to select non-matching lines.
    

Explained by step:

  • ls will list the files in current directory
  • grep -v new will return piped to that is not match new
  • xargs mv -t new will move the files piped to it from grep -v to the target directory

Solution 3:

Just use mv * subdir1 and ignore the warning.

You can just use mv * subdir1. You will see a warning message relating to trying to move subdir1 into itself, like this:

mv: cannot move 'subdir1' to a subdirectory of itself, 'subdir1/subdir1'

But it will move all of the other files and directories to subdir1 correctly.

An example:

$ ls
$ mkdir dir1 dir2 dir3      
$ touch file1.txt file2.txt file3.txt
$ mkdir subdir1
$ ls
#=> dir1  dir2  dir3  file1.txt  file2.txt  file3.txt  subdir1
$ mv * subdir1
#=> mv: cannot move 'subdir1' to a subdirectory of itself, 'subdir1/subdir1'
$ ls
#=> subdir1
$ ls subdir1
#=> dir1  dir2  dir3  file1.txt  file2.txt  file3.txt

Solution 4:

Simple idea. Assuming you are in /myuser, rename downloads to new, create a new downloads directory then move new into it.

mv downloads new # downloads is now called new
mkdir downloads # create new directory downloads
mv new downloads # move new into it.

Solution 5:

If you want to move all the files from a folder to one of its subfolders you can use the following command:

find /myuser/downloads/ -type d -name 'new' -prune -type f | xargs mv -t /myuser/downloads/new

It will find all the files and then move them to your subfolder.

@waltinator: added -type d -name 'new' -prune to prevent traversal of /myuser/downloads/new.