5

I have 100 files in a single folder including a folder called "target." I want to migrate all the files in this folder into the folder target (except for the target folder itself).

Is there an efficient terminal command to do this?

4 Answers 4

8

If there are only the files (and the directory target) in your directory, simply use mv, rather than find:

mv * target

It will complain that 'target' can't be moved on itself, but the files will all be in target afterwards.

4
  • 3
    +1. However, I would use target/ to make sure that I didn't accidentally rename all files to 'target'.
    – zpletan
    Commented Mar 29, 2012 at 3:25
  • 1
    As long as you've got more than one file to move, that shouldn't be a problem. It doesn't hurt though. Commented Mar 29, 2012 at 4:00
  • 1
    This does not handle hidden files.
    – Oli
    Commented Mar 29, 2012 at 12:13
  • Be aware that using this approach in scripts could give this error as fatal and abort the script!
    – Maf
    Commented Mar 23, 2023 at 22:06
2

Use this

$ mv target ..
$ mv * ../target
$ mv ../target .
2
  • This is clean and better to use in scripts.
    – Maf
    Commented Mar 23, 2023 at 22:05
  • Only if you are allowed to create something in ..
    – ohno
    Commented Mar 26, 2023 at 19:44
2

This works as well:

find . -maxdepth 1 ! -name target ! -name . -exec mv "{}" target \;

One of the key advantages of find over relying on bash completion is you get the hidden files at the same time. mv * ... won't do that.

You could perhaps go with something like:

mv -t target * .[^.]*

Or as James points out you could trim down the find command to only look at files... And as LoremIpsum pointed out if there are billions of them, using xargs would be slightly more efficient:

find . -maxdepth 1 -type f -print0 | xargs -0 mv -t target
2
  • 1
    You could probably simplify this to find . -maxdepth 1 -type f -exec ... to select by type rather than excluding particular names. Commented Mar 29, 2012 at 4:02
  • Maybe xargs could be used, too ?
    – LoremIpsum
    Commented Mar 29, 2012 at 8:14
0

The approach of moving the destination directory to a previous one then moving everything to it and finally moving it back to current directory if fine. The only problem is that it does not work for a git project directory where we need to keep the history.

So for a git directory just move like this: git mv * target -k

The -k option is used to skip move/rename errors

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .