Opening the book…
The xargs Command
xargs is a Unix command which can be used to build and execute commands from standard input.
Importance :
Some commands like grep can accept input as parameters, but some commands accepts arguments. This is where xargs came into the picture.
Syntax :
xargs [ OPTIONS ] [command]
xargs Command Options
| Options | Option Meaning |
|---|---|
| 0 | Input items are terminated by null character instead of white spaces. |
| -a file | Read items from file instead of standard input. |
| –delimiter = delim | Input items are terminated by a special character. |
| -E eof-str | Set the end of file string to eof-str. |
| -I replace-str | Replace occurrences of replace-str in the initial arguments with names read from standard input. |
| -L max-lines | Use at-most max-lines non-blank input lines per command line. |
| -p | Prompt the user about whether to run each command line and read a line from terminal. |
| -r | If the standard input does not contain any nonblanks, do not run the command. |
| -x | Exit if the size is exceeded. |
| –help | Print the summary of options to xargs and exit. |
| –version | Print the version no. of xargs and exit. |
Simply put xargs takes each input and applies the command to that input. Below are some examples of xargs:
# the file states.list contains 3 names, we cat the file and pipe the output to xargs mkdir - xargs # takes each line from the file and uses it as an argument to mkdir pbmac@pbmac-server $ cat states.list Alabama Wyoming Washington pbmac@pbmac-server $ cat states.list | xargs mkdir pbmac@pbmac-server $ ls Alabama states.list Washington Wyoming # now we use find, searching for type d (directory) and send all the output to xargs rmdir # the error message is becasue the find command also finds the . directory - the directory where we currently are pbmac@pbmac-server $ find . -type d | xargs rmdir rmdir: failed to remove '.': Invalid argument pbmac@pbmac-server $ ls pbmac@pbmac-server $ # there are 3 files ending in .txt, using the find command we pipe the output of the find to xzargs rm to remove # each .txt file. pbmac@pbmac-server $ ls one.txt states.list three.txt two.txt pbmac@pbmac-server $ find . -name "*.txt" | xargs rm pbmac@pbmac-server $ ls states.list
Adapted from:
"xargs command in Linux with examples" by Mandeep Singh, Geeks for Geeks is licensed under CC BY-SA 4.0
05-E.8.2: File Output Manipulation - xargs is shared under a CC BY-SA 4.0 license and was authored, remixed, and/or curated by LibreTexts.
The book could not be loaded just now.