How to use the xargs argument twice in the command on Linux?

Posted on In QA

`xargs` passes the argument once to the utility command specified. For example, xargs cat will cat every line passed to xargs. But how to use the xargs argument twice in the command on Linux? For example, to rename file to file.bak where file is from the stdin.

One solution is to write a small script like move.sh

file=$1
mv $file $file.bak

and invoke move.sh by xargs

xargs move.sh

However, it is very inconvenient that the move.sh should already there.

Are there other better methods?

You can use this trick to use the insert mode of xargs:

xargs -I@ bash -c "mv @ @.bak"'

Here, the -I@ tells xargs to replace ‘@’ in the command with the argument:

-I replace-str
Replace occurrences of replace-str in the initial-arguments with names read from standard input. Also, unquoted blanks do not terminate
input items; instead the separator is the newline character. Implies
-x and -L 1.

xargs manual

The command for xargs here is actually bash with arguments ‘-c “mv @ @.bak”‘ where ‘@’ will be replaced by xargs.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *