Usage of xargs linux command

The linux command line tool “xargs” is used to read data from standard input and later execute a command based on standard input. The typical use cases for this command is while working on file / directory operations along with other commands like rm, grep, mkdir etc.


The syntax to use this command is

$ <my command 1 > | xargs < my command 2>

Note: on the above command, “|” is used to pass the stdout to xargs.

Here are some examples

Using xargs with grep

$ find . -name 'search type' | xargs grep 'target string to find on the file'
$ find . -name Makefile | xargs grep snd-acp3x-rn.o
./kernels/4.18.0-305.3.1.el8.x86_64/sound/soc/amd/renoir/Makefile:snd-acp3x-rn-objs := acp3x-rn.o
./kernels/4.18.0-305.3.1.el8.x86_64/sound/soc/amd/renoir/Makefile:obj-$(CONFIG_SND_SOC_AMD_RENOIR_MACH) += snd-acp3x-rn.o

Using xargs with find

Use xargs with find to run commands like rm or mv

$ find <directory> -name "search term" -type f | xargs <command>
$ ls
file1.doc file1.txt file2.doc file2.txt
$ find . -name "*.txt" -type f | xargs ls
./file1.txt ./file2.txt
$ find . -name "*.txt" -type f | xargs rm -f
$ ls
file1.doc file2.doc

To remove blank spaces in string

xargs can be used to remove blank spaces from a string, as shown below

$ echo " Hello World ! " | xargs
Hello World ! 

Usage as a Word Count

xargs can be used to print the number of lines, words and characters in files. In the example below, wc is use to list the number of lines on the files, number of words and number of characters on each of them.

$ ls *txt | xargs wc
1 2 12 file1.txt
1 7 28 file2.txt
2 9 40 total

Additional Switches on XARGS

Control Number of Arguments

Use the “-n” switch to control the number of arguments passed to xargs as demonstrated in the example below

$ echo "This is Hello World Demo String" | xargs -n 1
$ echo "This is Hello World Demo String" | xargs -n 2
This is
Hello World
Demo String

View xargs executed command

Use “-t” switch to view the commands executed by xargs

$ <command> | xargs -t <command>
$ find . -name "*.doc" -type f | xargs -t ls
ls ./file1.doc ./file2.doc
./file1.doc ./file2.doc

0 Comments on Usage of xargs linux command

Leave a Comment

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

You Might Be Interested In