Yves
Yves

Reputation: 12371

How to understand xargs

Saying that I have two files t1 and t2, they have the same content: abc.

Now I want to delete all files, who contains the string abc.

So I tried to execute the command: grep -rl abc . | rm but it doesn't work.

Then I add xargs: grep -rl abc . | xargs rm and it works.

I can't understand clearly what xargs did.

Upvotes: 1

Views: 205

Answers (2)

Arndt Jonasson
Arndt Jonasson

Reputation: 854

rm doesn't read from standard input (except when prompting, like with -i) but takes its arguments on the command line. That's what xargs does for you: read things from standard input and give them to rm as arguments.

Example with echo:

$ (echo a; echo b; date) | xargs echo
a b tor 12 apr 2018 14:18:50 CEST

Upvotes: 0

Giacomo Catenazzi
Giacomo Catenazzi

Reputation: 9523

grep puts the output as stdout. But rm cannot process data from stdin (the pipe links both).

You want instead, that the output of grep is put as argument of rm. So xargs command "convert" stdin into arguments of xargs first argument, and it call the command (the first argument).

As alternative, you could do

rm `grep -rl abc .`

or

rm $(grep -rl abc .)

But xargs handles well also the case where there are too many arguments for a single call of the command. The above command will give you shell error (argument string too long).

Upvotes: 2

Related Questions