Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

As we all know, in Linux, pipe | command can be implemented to transform the left side of the command standard output to the standard input to provide the right command is used, but some command does not accept delivery pipeline, such as ls, echo, etc., there are many commands do not support the standard input as a parameter, can only be specified in the execution of command line parameters, This leads to cannot use pipe | command transmission parameters. The xargs command takes standard input and converts it to command-line arguments.

Syntax format

command | xargs [options] command
Copy the code

Common parameters are as follows:

  • -a file: Read from a file as standard inputstdin
  • -d: By default,xargsUsing line breaks and Spaces as separators,-dYou can change the delimiter
  • -p: Prints the command to be executed and asks the user whether to execute it
  • -t: Prints the command to be executed and executes it without user confirmation
  • - L line numberIf the standard input contains more than one line,-LThe argument specifies how many lines to use as a command line argument
  • - n number: Specifies how many items to use as command line arguments at a time
  • --max-procs: How many processes are used to execute commands in parallel,-max-procs 0The number of processes is not limited

Using the instance

Said above, there are a lot of command does not support all the standard input as a parameter, lead to cannot use pipe | command transmission parameters, however, xargs and pipe when used together, is ok.

Such as:

The find command accepts pipe pass parameters find | grep testCopy the code
#The cat command does not accept pipe pass arguments
cat test.txt
# hello xargs!
echo "test.txt" | cat
# test.txt
[root@centos7 test]#
Copy the code
#Xargs converts standard input to command line arguments
echo "test.txt" | xargs cat
# hello xargs!
Copy the code

As you can see, the cat command does not pipe parameters. We try to pass parameters to cat through standard input, but the file name is displayed. Xargs passes echo output as standard input to cat on the right, which is executed as an argument to the command.

Use the -d argument to specify the TAB character \t as the delimiter:

echo -e "a\tb\tc" | xargs -d "\t" echo
# a b c
Copy the code

Print the command to execute with the -p argument, asking whether to execute:

find ./ | xargs -p rm -f rm -f ./ ./test_ae ./test_ac ./test_am ? .Copy the code

Original is not easy, if small partners feel helpful, please click a “like” and then go ~

Finally, thank my girlfriend for her tolerance, understanding and support in work and life!