Thursday, December 29, 2022

Linux xargs command

 

xargs, a UNIX and Linux command for building and executing command lines from standard input. Examples of cutting by character, byte position, cutting based on delimiter and how to modify the output delimiter.



The xargs command in UNIX is a command line utility for building an execution pipeline from standard input. Whilst tools like grep can accept standard input as a parameter, many other tools cannot. Using xargs allows tools like echo and rm and mkdir to accept standard input as arguments.



By default xargs reads items from standard input as separated by blanks and executes a command once for each argument. In the following example standard input is piped to xargs and the mkdir command is run for each argument, creating three folders.


echo 'one two three' | xargs mkdir

ls

one two three


xargs v exec

The find command supports the -exec option that allows arbitrary commands to be performed on found files. The following are equivalent.



find ./foo -type f -name "*.txt" -exec rm {} \; 

find ./foo -type f -name "*.txt" | xargs rm


time find . -type f -name "*.txt" -exec rm {} \;

0.35s user 0.11s system 99% cpu 0.467 total


time find ./foo -type f -name "*.txt" | xargs rm

0.00s user 0.01s system 75% cpu 0.016 total



references:

https://shapeshed.com/unix-xargs/


No comments:

Post a Comment