13 Examples That Showcase the xargs Command in Linux 

xargs command in linux

Most Linux commands can accept input directly from the standard input (stdin). However, there are commands and utilities that only accept arguments as input. 

We recommend the xargs command in Linux for these commands. This utility takes the input data and converts it into arguments for a specified command.

In this tutorial, we will explore the xargs command in Linux. Next, we will discuss how you can use this utility with several common commands that you use for regular everyday tasks. 

Table Of Contents

  1. An Overview of the xargs Command in Linux
    1. The Prerequisites
    2. Example #1: Integrate xargs with the find Command
    3. Example #2: Use xargs with the grep Utility
    4. Example #3: Execute Multiple Commands with xargs
    5. Example #4: Reading Items from a File
    6. Example #5: Locate and Archive Images with the tar Command
    7. Example #6: Display Output with the print Command
    8. Example #7: Confirm execution of the xargs Commands
    9. Example #8: Limit the Output to a Specific Number of Items Per Line
    10. Example #9: Define a Custom Delimiter
    11. Example #10: Display Every User Account on a Linux System
    12. Example #11: Eliminate White Spaces in a String
    13. Example #12: Enumerate the Number of Lines, Words, and Characters in Each File
    14. Example #13: Replicate File Across Multiple Directories
  2. Conclusion
  3. FAQs

An Overview of the xargs Command in Linux

The xargs command solves the common challenge posed by commands that only take arguments as input. The utility takes the output of commands and converts them into arguments for commands such as rm, cp, and mkdir

The most common use of this utility is to include the standard input into command pipelines. 

13 Examples of the xargs Command

The best way of understanding the role of xargs command is to see it in action in taking care of operational tasks. We will now go into the details of these scenarios and see how xargs helps you solve common challenges.

The Prerequisites

Before diving into the details of the scenarios, make sure you have the following:

  • A system running a mainstream Linux distribution
  • A user account with root or sudo privileges

Example #1: Integrate xargs with the find Command

In a pipeline, the find command is frequently used before xargs, supplying a list of files that xargs can then process. The structure of the command is as follows:

# find [location] -name "[search-term]" -type f | xargs [command]

Consider the following example:

# find . -name ‘*.sh’ -type f | xargs rm-f

Integrate xargs with the find Command

In this example, we used the find command to locate all files ending in .sh. These files are then directed to xargs through a pipeline, which employs the rm command for deletion. You can easily extend this command to delete directories by changing the parameters for the find command. 

Note that xargs, by default, excludes files with spaces in their names. You can use the -print0 option with find and the -0 option with xargs. The command, in this case, will be as follows:

# find [location] . -name "[search-term]" -type f -print0 | xargs -0 [command]

find [location]

Example #2: Use xargs with the grep Utility

You can combine xargs with the grep utility to locate a specific string within the file list generated by the find command.

find . -name '[search-term]' | xargs grep '[string-to-find-in-files]'

Consider the following example where the find command searched for all files bearing the .txt extension, which were then relayed to xargs. Subsequently, xargs executed the grep command on these files.

Use xargs with the grep Utility

Example #3: Execute Multiple Commands with xargs

We recommend the -I option for executing multiple commands using xargs

Consider the following example where we used the cat command to display the contents of the file4.txt. This is passed on to xargs which uses mkdir to create a directory for each word of the contents of the file4.txt: 

# [command-providing-input] | xargs -I % sh -c '[command-1] %; [command-2] %'

Execute Multiple Commands with xargs

Example #4: Reading Items from a File

As previously noted, xargs typically processes standard input. You can use the -a option to have it read input from a file. The command syntax in this context will be as follows:

# xargs -a [filename]

Consider the following command where we provided the input from a file:
# xargs -a example.txt

Reading Items from a File

Example #5: Locate and Archive Images with the tar Command

You can create a tar.gz archive file of the images you can find using the find command with the xargs command. 

The command syntax of this command is as follows: 

# find [location] -name "[search-term]" -type f -print0 | xargs -0 tar -cvzf [tar-gz-archive-name]

Locate and Archive Images with the tar Command

Example #6: Display Output with the print Command

We recommend the -t option to display the commands that xargs executes in the standard output. The syntax of the command in this case would be as follows:

# [command-providing-input] | xargs -t [command]

Display Output with the print Command

As you can see in the above example, xargs applied the mkdir command to the entire string supplied by the echo command.

Example #7: Confirm execution of the xargs Commands

We recommend using the -p option with the xargs command when considering critical irreversible operations, such as deleting files and folders. This option inserts a confirmation prompt for confirmation before executing the commands.

The syntax, in this case, will be as follows: 

# [command-providing-input] | xargs -p [command]

Confirm execution of the xargs Commands

Example #8: Limit the Output to a Specific Number of Items Per Line

You can control the number of arguments processed simultaneously by xargs with the -n option. This option specifies the number of arguments xargs can process/output in a line. The syntax of the command is as follows:

# [command-providing-input] | xargs -n [number] [command]

Consider the following example. Here xargs takes the string from the echo command and splits it into three parts. It then executes the echo command for each of the parts:

# echo “1 2 3 4 5 6 7 8 9” | xargs -n 3

Limit the Output to a Specific Number of Items Per Line

Example #9:Define a Custom Delimiter

By default, xargs employs a blank space as its delimiter. You can change this default with the -d option, followed by a single character or an escape sequence like \n for a new line.

The syntax of the command in this case would be as follows:

# [command-providing-input] | xargs -d [new-delimiter] | xargs [command]

Consider the following command where we used * as the delimiter for the mkdir command:

# echo “folder*folder2*folder3” | xargs -d* | xargs mkdir

Define a Custom Delimiter

Example #10: Display Every User Account on a Linux System

You can combine xargs for streamlining the arrangement of the outputs of command like cut. Consider the following example:

# cut -d: -f1 < /etc/passwd | sort | xargs

In this command, we used the cut command to access the /etc/passwd file and used the : delimiter to truncate the beginning of each line within the file. Subsequently, the output is directed through a pipe to the sort command, which arranges the strings received and passes it to xargs for display.

Display Every User Account on a Linux System

Example #11: Eliminate White Spaces in a String

Given that xargs disregards whitespace while parsing arguments, the following command proves handy for stripping extra blank spaces from input strings. The syntax of the command will be as follows:

# echo "[string-with-unnecessary-spaces]" | xargs

Consider the following command:

# echo “   line with space” | xargs

Eliminate White Spaces in a String

Example #12: Enumerate the Number of Lines, Words, and Characters in Each File

You can combine xargs in conjunction with the wc command to list down the files along with their respective line, word, and character counts. 

Consider the following example where the ls command filters out and passes only the files containing the term example to the xargs command. The xargs command then uses the wc command to this list:

ls *example* | xargs wc

Enumerate the Number of Lines, Words, and Characters in Each File

Example #13: Replicate File Across Multiple Directories

You can use the xargs command to duplicate files across multiple directories. The syntax is straightforward:

# echo [directory-1] [directory-2] | xargs -n 1 cp -v [filename]

Replicate File Across Multiple Directories

In this command, the echo command furnishes directory names, and xargs employs the cp command to duplicate the specified file into each of the directories.

Also Read: lsof Command in Linux with Examples

Conclusion

This tutorial covered the xargs command and showcased more than ten scenarios that demonstrated the use of this versatile command.

You can now optimize daily tasks and streamline operations by using the xargs command. You can build effective pipelines that use several commands to accomplish comprehensive tasks. 

If you’re looking for a robust server for your Linux projects, we offer the best dedicated server pricing and deliver instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated servers, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.

FAQs

Q. What is the xargs command in Linux?

The xargs command in Linux is a command-line utility that is used to build and execute commands from standard input. It can be used to take input from a pipe or a file and then convert it into command lines or arguments.

Q. What are some essential use cases for the xargs command in Linux?

Essential use cases for the xargs command in Linux include file management, input from the standard input stream, performing complex or repetitive tasks, and as a handy tool for executing commands with arguments.

Q. Can xargs effectively process log files?

Yes, xargs, combined with bash commands like grep or sed, efficiently extracts, filters, or manipulates data from log files.

Q. How can the xargs command be used with package managers in Linux?

The xargs command can be used with package managers in Linux to execute multiple package management commands quickly and efficiently. It can take the output of one command, such as listing installed packages, and use it as input for another package management operation.

Q. What are the basic command-line options for using the xargs command in Linux?

The basic command-line options for using the xargs command in Linux include -I to specify a placeholder for the input, -L to limit the number of arguments passed to each command, and -P to specify the maximum number of commands to run in parallel.

Q. How can xargs be utilized for directory traversal and management tasks?

Xargs is an indispensable, valuable tool for traversing directories and executing commands on multiple files within a directory tree. By combining it with commands like find, administrators can execute complicated tasks like searching for files, deleting files matching specific criteria, or moving files to a temporary directory for further processing.

Q. Can xargs handle file paths with spaces or special characters?

Yes, xargs excels at handling file paths with spaces or special characters. By default, it uses newline characters to separate input items, ensuring that filenames containing spaces or special characters are processed correctly. Additionally, users can enclose filenames in single quotes or double quotes to prevent them from being misinterpreted by xargs or other commands in the pipeline.

Q. How does the current location affect xargs basic usage?

Xargs operates in the current working directory by default, allowing users to execute commands seamlessly within their working directory context.

Q. How can xargs assist in server administration tasks?

Xargs is a powerful tool for automating server administration tasks. For instance, it can be used to query multiple servers simultaneously and execute commands based on the results. By leveraging the parallel execution capability of xargs, administrators can efficiently manage and monitor large server environments.

Q. How do xargs benefit developers and advanced users?

Xargs enhances the workflow of developers and advanced users by seamlessly integrating with developer tools, supporting command-line flags, and enabling efficient management and manipulation of data.

Q. How can novice users quickly grasp the usage of xargs?

Novice users can quickly get started with xargs by following a quick guide that outlines its essential usage and benefits. Additionally, they can check out resources such as tutorials, documentation, and online forums to deepen their understanding of this essential tool. By familiarizing themselves with the simplest usage and practical applications of xargs, novice users can efficiently leverage its capabilities for various command-line tasks.