25

I am trying this and it's not working:

ls file_* | xargs mv {} temp/

Any ideas?

Peter Mortensen
  • 12,090
  • 23
  • 70
  • 90

5 Answers5

33

On OS X:

ls file_* | xargs -J {} mv {} temp/

On Linux:

ls file_* | xargs -i {} mv {} temp/
Amadan
  • 1,837
  • 1
  • 12
  • 12
10

Use -t "specify target directoty" at mv, it should work moving files* to destination directory /temp

ex:- #ls -l file* | xargs mv -t /temp

Ratheesh
  • 101
  • 1
  • 2
8

find . -name "file_*" -maxdepth 0 -exec mv {} temp/ \;

find is better than ls where there might be more files than the number of program arguments allowed by your shell.

David-SkyMesh
  • 211
  • 2
  • 8
  • 2
    Note that the question suggests a desire to process only the `file_*` files in the current directory, while `find` (without additional options) will search the entire directory tree under the current directory. – Scott - Слава Україні Jan 08 '13 at 04:20
  • 1
    Yes, true. Add `-maxdepth 0` to prevent this. –  Jan 08 '13 at 04:22
  • "better" is subjective. More powerful, more complex, and slower; and while `mv` doesn't care if you process files together or individually, some other uses might. – Amadan Jan 08 '13 at 04:25
  • Edited (added `-maxdepth 0`) –  Jan 08 '13 at 07:13
5

As suggested by @user1953864: {-i, -J} specify a token that will be replaced with the incoming arguments.

For example ls:

something.java  exampleModel.java  NewsQueryImpl.java  readme someDirectory/

Then to move all java files into the someDirectory folder with xargs would be as follows:

On Linux

ls *.java | xargs -i mv {} someDirectory/

On MacOS

ls *.java | xargs -J mv {} someDirectory
mdk
  • 51
  • 1
  • 1
0

Another solution might be:

 for f in file_* ; do
   mv $f temp/$f
 done

The disadvantage is that it forks a new mv process for each file.