xargs 2022-08-03
The xargs
command is used in a UNIX shell to convert input from standard input into arguments to a command.
xargs
命令实际上就是将所有空格、制表符和分行符都替换为空格并【压缩到一行上显示】,这一整行将作为一个字符串传入到目标命令中,而它支持的option决定了将stdin传来的结果转化成不同的字符串的方式,如处理分隔符的问题、转化成多个字符串分批执行的问题
common usage:
command1 | xargs command2
- uses a single command after the piped operation
eg.ls | xargs ls
- run multiple commands along with xargs.
eg.
# echo "file1 file2 file3" | xargs -t -I % sh -c '{ touch %; ls -l %; }'
- 常用的option
-
-I replace-str
Replace occurrences of replace-str in the initial-arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1.
eg.$ ls | xargs -p -I % sh -c 'echo %; ls -l %' sh -c echo files; ls -l files?...
ls | xargs -p -I % sh -c 'echo %; ls -l %'
%符号都被替换成ls的xargs结果,因此等价于sh -c echo files; ls -l files
-
-0
使用null character
分割输入并且不做任何转义
Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally,所有字符都是字面义而不会转义). Disables the end of file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes.
The GNUfind -print0
option produces input suitable for this mode. egfind . -print0 | xargs -0 echo
man find
可以看到find
命令支持一个expression叫-print0
,它的输出就是以null character
分隔各个item-print0
True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses).
This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs.