Mastering xargs: Transform Input Streams into Powerful Command Arguments
This guide explains how the xargs utility filters and converts standard input into command-line arguments, details its syntax and common options, and provides practical examples demonstrating multi‑line to single‑line conversion, custom delimiters, and interactive command execution.
xargs: Filter
Function Description
xargs is a filter that passes arguments to other commands and serves as a tool for chaining multiple commands. It excels at converting standard input data into command-line arguments, handling pipelines or stdin and turning them into parameters for a specific command.
xargs can also transform single‑line or multi‑line text input into other formats, such as converting multi‑line to single‑line or vice versa. Its default command is echo and the default delimiter is a space. This means input passed through a pipe to xargs contains newlines and blanks, which xargs replaces with spaces, making it a key component for building single‑line commands.
Command Syntax
xargs [options]Common Options
-n : multiple line output
-d : custom delimiter
-I : specify a replacement string {}
-t : print the command executed by xargs
-p : prompt for confirmation before executing each command
Reference Examples
Example 1
xargs used as a replacement tool, reads input data, reformats and outputs:
// (1) Define a test file with multiple lines of text data:
# cat data.txt
a b c d e f g
h i j k l m n
o p q
r s t
u v w x y z
// (2) Multi-line input single-line output:
# cat data.txt | xargs
a b c d e f g h i j k l m n o p q r s t u v w x y z
// (3) Combine -n option for multi-line output:
# cat data.txt | xargs -n6
a b c d e f
g h i j k l
m n o p q r
s t u v w x
y z
// (4) Combine -d option to customize a delimiter:
# echo "myQnameQisQlinuxer" | xargs -dQ
my name is linuxerExample 2
Read stdin, format the parameters and pass them to a command:
// Copy all jpg files to /images directory:
# ls *.jpg | xargs -n1 -I cp {} /images
// Print the commands xargs executes:
# ls | xargs -t -I{} echo {}
// Prompt for confirmation before each command, useful for precise deletions:
# find . -maxdepth 1 -name "*.log" | xargs -p -I{} rm {}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
