xargs: Build and Execute Command Lines from Standard Input
August 12th, 2024 12:44 PM Mr. Q Categories: Command
The xargs
command is used to build and execute command lines from standard input. It reads items from standard input, separated by spaces, newlines, or other delimiters, and executes a specified command with those items as arguments.
Command:
xargs [options] [command [arguments]]
Examples
- Use
xargs
to Remove Files
find . -name "*.tmp" | xargs rm
Sample Input:
file1.tmp
file2.tmp
Sample Output:
(No output; the files are deleted)
- Pass Arguments to a Command
echo "file1.txt file2.txt" | xargs cat
Sample Input:
file1.txt file2.txt
Sample Output:
(Contents of file1.txt and file2.txt concatenated and displayed)
- Use
xargs
with a Custom Delimiter
echo "file1:file2:file3" | xargs -d: -I {} cp {} /destination/
Sample Input:
file1:file2:file3
Sample Output:
(Files file1, file2, and file3 copied to /destination/)
- Limit the Number of Arguments
echo "file1.txt file2.txt file3.txt file4.txt" | xargs -n 2 cp -t /destination/
Sample Input:
file1.txt file2.txt file3.txt file4.txt
Sample Output:
(Files file1.txt and file2.txt copied to /destination/)
(Files file3.txt and file4.txt copied to /destination/)
- Execute a Command with Input from a File
xargs -a filelist.txt wc -l
Sample File (filelist.txt
):
file1.txt
file2.txt
Sample Output:
10 file1.txt
20 file2.txt
30 total
The xargs
command is a powerful utility for handling command line arguments and performing batch operations on files or data.