25

I am trying this and it's not working:

ls file_* | xargs mv {} temp/

Any ideas?

1
  • Anyone with a multi file move version of this? (xargs -n10 for example) Apr 14, 2016 at 9:42

5 Answers 5

33

On OS X:

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

On Linux:

ls file_* | xargs -i {} mv {} temp/
8
  • 1
    On Linux, at least, the / at the end is optional. You can include it if you want, but it’s not necessary. Jan 8, 2013 at 4:20
  • 5
    @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, 2013 at 4:23
  • 17
    You might need to say -i{}, without a space. Or say -I {}. Jan 8, 2013 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, 2016 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, 2016 at 3:40
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

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.

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

You must log in to answer this question.