How to use the xargs command in Linux?
The xargs command in Linux is used to read data from stdin and pass it as arguments to another command. It is primarily used for handling commands that have a large number of arguments. Below is the basic syntax and usage example of the xargs command.
Basic syntax: xargs [options] [command]
常用选项:
-0:使用null来分隔,而不是使用空格或换行符。
-I<替换字符串>:用<替换字符串>替换参数。
-n<参数个数>:每次执行命令时使用的参数数量。
-t:在执行命令之前输出即将执行的命令。
Example of usage:
- Pass each line of text from stdin as a parameter to the echo command:
echo “one two three” | xargs echo
Output: one two three - Pass each line of text read from the file as a parameter to the ls command:
cat file.txt | xargs ls
Output: file1.txt file2.txt file3.txt - Pass the parameters in stdin line by line to the grep command and search for matching lines in the file:
cat file.txt | xargs -I{} grep {} file_to_search.txt
Output: matching lines. - Pass the arguments in stdin to the command using null as a delimiter:
echo “one two three” | xargs -0 echo
Output: one two three - Use two parameters every time the command is executed:
echo “one two three” | xargs -n2 echo
Output:
one two
three
These are just some common uses of the xargs command. Depending on the specific needs, you can also combine xargs with other commands and options. For more detailed information about the xargs command, you can use the man xargs command.