Open In App

Running multiple commands with xargs

Xargs is a command utility in Unix and Unix-like operating systems. It is used to build and execute commands from standard input which can be the output of the other command or data files. In this article, we will see how to run multiple commands with xargs.

Syntax of `xargs` multiple command in Linux

command1 | xargs [options] command2

Understanding of xargs

Xargs is the versatile command-line utility that reads data from the standard input (stdin) and executes a specified command with the input as arguments. It is very useful for scenarios where a list of items needs to be processed by another command.

There are many uses of “xargs” with multiple commands. Here, we are demonstrating some examples of xargs.



Creating Directories from a “echo” command

We can generate multiple folders or files using the echo command with xargs command. There are the following steps for making the folders using the xargs command.

echo "one two three" |  xargs mkdir

Output

Deleting files with xargs Command:

Xargs command also deletes the specific file extension files. We can find the specific file using the find command and pass the find command output to the xargs command using the pipes. See the following steps:

find . -name "*.txt" | xargs rm

In this example, first we will filter the fils using the find command then passed those file as arguments passed to the ‘rm’ command. The below image demonstrates how it works.

Output

Renaming Files with xargs

Suppose you wan to rename all files with a “.txt” extension to have a “.php” extension. You use find command with xargs and mv for this task. Follow the following steps.

find . -name "*.txt" | xargs -I {} sh -c 'mv {} $(basename {} .txt).php'

This command uses ‘-I {}’ to specify a placeholder,and the ‘sh -c’ command allows the use of shell syntax for more complex operation. The ‘mv’ command renames each file by replacing the ‘.txt’ extension with ‘.php’. The following image demonstrates.

Output

Xargs with three arguments

We can also used xargs with three arguments. In this example, we will see, how we can do this. See the following steps

Command:

echo "arg1 arg2 arg3" | xargs -n 3 echo "Custom command:"

Output

Remove Delimeter

We can also remove delimiter using the xargs command. In this example, we are going to remove delimiter in the command using xargs command. Follow the following steps.

Command:

echo "arg1:arg2:arg3" | xargs -d: -n 3 echo "Delimited command:"

Output

Conclusion

Xargs is very useful command line utility that can used day to day task. In this article , we have almost explained various multiple command runs with xargs. There are more example of this amazing tool. This is useful for processing multiple items in a list with a single command.

Article Tags :