Hack 22. Xargs Command Examples

xargs is a very powerful command that takes output of a command and pass it as argument of another command. Following are some practical examples on how to use xargs effectively.

Xargs Example 1:

When you are trying to delete too many files using rm, you may get error message: /bin/rm Argument list too long – Linux. Use xargs to avoid this problem.

# find ~ -name ‘*.log’ -print0 | xargs -0 rm -f

Xargs Example 2:

Get a list of all the *.conf file under /etc/. There are different ways to get the same result. Following example is only to demonstrate the use of xargs. The output of the find command in this example is passed to the ls –l one by one using xargs.

# find /etc -name "*.conf" | xargs ls –l

Xargs Example 3:

If you have a file with list of URLs that you would like to download, you can use xargs as shown below.

# cat url-list.txt | xargs wget –c

Xargs Example 4:

Find out all the jpg images and archive it.

# find / -name *.jpg -type f -print | xargs tar -cvzf images.tar.gz

Xargs Example 5:

Copy all the images to an external hard-drive.

# ls *.jpg | xargs -n1 -i cp {} /external-hard-drive/directory

Comments on this entry are closed.

  • Will Bryant April 8, 2013, 3:32 am

    I don’t think your tar example is very wise. It will recreate the archive for each block of files that xargs gives it, meaning you will only get some of the files you wanted in the archive. Of course, if you don’t have many files in the list, they might all make it in, but then you wouldn’t need xargs.

  • RAJESH May 27, 2013, 11:09 am

    Hi Dude,

    Great article. I have taken note.

    Cheers,
    Raj

  • Ravi Dubey June 12, 2013, 3:23 am

    i have file names with Space and special character.
    | args -rm is not able to remove these files. Can you please help!!

  • gmu October 1, 2013, 2:24 am

    @Rubi Dubey: If want to delete some files found by the find command, you don’t need the xargs command. You can also use the exec parameter from the find:
    find / -name “all_my_files_to_delete_*” -print -exec echo “rm {}” \;
    (after this only print output you have to change echo “rm {}” with rm {})

  • kishan April 12, 2014, 1:25 am

    Can you force overwrite the copy command??

    like if I write

    # cp test1 /home
    cp: overwrite `/home/test1′?

    How can we force it not show this overwrite line…
    I tried -Rf but not working still I’m seeing this….