Xargs

From TBP Wiki
Jump to: navigation, search
xargs is a command on Unix and most Unix-like operating systems used to build and execute commands from standard input. It converts input from standard input into arguments to a command.

Some commands such as grep and awk can take input either as command-line arguments or from the standard input. However, others such as cp and echo can only take input as arguments, which is why xargs is used instead.

Usage

Pipe output from cat and grep into sed to replace "foo" with "bar" within file.txt:

   cat foobar.txt | grep bar | xargs -I '{}' sed 's/foo/{}/g' file.txt

Randomly shuffles output of ls and grep of "/dir1/dir2/us1234.thing.txt" and only prints up to the first instance of "." due to awk:

   ls /dir1/dir2/ |grep us |awk -F "." '{print $1}' | xargs shuf -n1 -e