The Linux xargs command

  

xargs is a filter that passes arguments to commands and is a tool for combining multiple commands. It splits a data stream into small enough blocks to facilitate filtering and command processing. Normally, xargs reads data from the pipe or stdin, but it can also read data from the output of the file. The default command for xargs is echo, which means that input passed to xargs via the pipeline will contain newlines and whitespace, but with xargs processing, newlines and whitespace will be replaced by spaces.

xargs is a powerful command that captures the output of one command and passes it to another. Here are some practical examples of how to use xargs effectively.

1. When you try to delete too many files with rm, you may get an error message: /bin/rm Argument list too long. Use xargs to avoid this problem

find ~ - Name ‘*.log’ -print0 |  Xargs -0 rm -f


2. Get a list of all files ending in *.conf under /etc/. There are several different ways to get the same result. The following example only It's a demonstration of how to use xargs. In this example, xargs passes the output of the find command to ls -l

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

3. If you have a file containing a lot of URLs you wish to download, you can use xargs to download all links

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



4. Find all jpg files and compress it

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


5. Copy all image files to an external hard drive

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


EXAMPLESfind /tmp -name core -type f -print |  Xargs /bin/rm -fFind files named core in or below the directory /tmp and delete them. Note that this will works incorrectly if there are any filenames containing newlines or spaces.

find /tmp -name core - Type f -print0 |  Xargs -0 /bin/rm -fFind files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing spaces or newlines are correctly handled.

find /Tmp -depth -name core -type f -deleteFind files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) To launch rm and we don't need the extra xargs process).

cut -d: -f1 < /etc/passwd |  Sort |  Xargs echoGenerates a compact listing of all the users on the system.

xargs sh -c 'emacs "$@" < /dev/tty' emacsLaunches the minimum number of copies of Emacs needed, one after The other, to edit the files listed on xargs' standard input. This example achieves the same effect as BSD's -o option, but in a more flexible and portable way.

Copyright © Windows knowledge All Rights Reserved