24

I am trying this and it's not working:

ls file_* | xargs mv {} temp/

Any ideas?

migrated from stackoverflow.com Jan 8 '13 at 7:45

This question came from our site for professional and enthusiast programmers.

  • Anyone with a multi file move version of this? (xargs -n10 for example) – Gert van den Berg Apr 14 '16 at 9:42
31

On OS X:

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

On Linux:

ls file_* | xargs -i {} mv {} temp/
  • 1
    On Linux, at least, the / at the end is optional. You can include it if you want, but it’s not necessary. – Scott Jan 8 '13 at 4:20
  • 4
    @user1953864: -i (or -J) specify a token that will be replaced with the incoming arguments, instead of them just being tacked onto the end. man xargs – Amadan Jan 8 '13 at 4:23
  • 14
    You might need to say -i{}, without a space. Or say -I {}. – Scott Jan 8 '13 at 4:52
  • 1
    I notice that using "%" in place of "{}" also works - what does % mean and what does {} mean? Example: ls file_* | xargs -I% mv % temp/ – dmonopoly Jun 16 '16 at 3:19
  • 3
    @dmonopoly: They don't mean anything. Whatever the parameter to -i is, it is getting replaced. ls file_* | xargs -iFOO mv FOO temp/ works exactly the same. – Amadan Jun 16 '16 at 3:40
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.

  • 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 8 '13 at 4:20
  • 1
    Yes, true. Add -maxdepth 0 to prevent this. – David-SkyMesh Jan 8 '13 at 4: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 8 '13 at 4:25
  • Edited (added -maxdepth 0) – David-SkyMesh Jan 8 '13 at 7:13
8

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

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

3

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
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.

Your Answer

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