Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Jun 242010
 

xargs when the filename contains a newline

Answer:

It is always handy to combine the power of find and xargs for a lot of tasks, such as

# find /tmp -type f | xargs rm -rf

However, the command will failed if the a file contains a newline character. To solve this, you can do like below.

# find /tmp -type f -print0 | xargs -0 rm -rf

Now the file list returned by the find command is terminated by a null character, so it will not mixed with the newline character if they are part of the filename. Also, the xargs -0 option will treat the null character as the delimiter (rather than newline).

Dec 312009
 

Run tasks in parallel with xargs

Answer:

xargs provided a very simple to parallel tasks, e.g. setting P=3 means run 3 processes in parallel

seq 1 10 | xargs -n 1 -P 3 echo

Result:

1
2
3
4
5
7
6
9
8
10

Try to run the command several times, you might notice that number's order might be changed.

Why? Since they are running in parallel and some numbers finished first and some later!

Dec 312009
 

How to adjust the argument position in xargs?

Answer:

Sometimes you might want to adjust the argument position when using the xargs command, e.g.

echo "foo" | xargs echo "bar"

It gives:

bar foo

Instead, you want the piped argument "foo" to be inserted before the "bar", you can use

echo "foo" | xargs -i echo {} "bar"

Now it gives:

foo bar

That's very handy