How can I move files with xargs on Linux?

32,008

Solution 1

On OS X:

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

On Linux:

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

Solution 2

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

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

Solution 3

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.

Solution 4

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
Share:
32,008
Admin
Author by

Admin

Updated on September 18, 2022

Comments

  • Admin
    Admin over 1 year

    I am trying this and it's not working:

    ls file_* | xargs mv {} temp/
    

    Any ideas?

  • Scott - Слава Україні
    Scott - Слава Україні over 11 years
    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 - Слава Україні
    Scott - Слава Україні over 11 years
    On Linux, at least, the / at the end is optional. You can include it if you want, but it’s not necessary.
  • Admin
    Admin over 11 years
    Yes, true. Add -maxdepth 0 to prevent this.
  • Amadan
    Amadan over 11 years
    @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
    Amadan over 11 years
    "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.
  • Scott - Слава Україні
    Scott - Слава Україні over 11 years
    You might need to say -i{}, without a space. Or say -I {}.
  • Admin
    Admin over 11 years
    Edited (added -maxdepth 0)
  • dmonopoly
    dmonopoly almost 8 years
    I notice that using "%" in place of "{}" also works - what does % mean and what does {} mean? Example: ls file_* | xargs -I% mv % temp/
  • Amadan
    Amadan almost 8 years
    @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.
  • Matthias Braun
    Matthias Braun almost 6 years
    -i is deprecated according to the manual, use -I (uppercase i) instead.