Linux下xargs命令的用法小结


=Start=

缘由:

下午在处理一些脚本问题的时候用到了xargs命令的一些不那么常用的用法,在解决了实际问题之后顺便总结一下,方便以后直接参考。

正文:

参考解答:

默认情况下,xargs命令会将输入的内容以空格连接起来,比如:

$ for i in $(seq 1 20); do
echo "line"$i
done >>test.txt

$ cat test.txt
line1
line2
...

$ cat test.txt | xargs
line1 line2 line3 line4 line5 line6 line7 line8 line9 line10 line11 line12 line13 line14 line15 line16 line17 line18 line19 line20

如果我们希望修改一下xargs的输出格式,比如将「空格」换成「将每个元素用双引号括起来再用空格连接」,可以通过下面的命令实现:

$ cat test.txt | xargs -n1 printf '"%s" '
"line1" "line2" "line3" "line4" "line5" "line6" "line7" "line8" "line9" "line10" "line11" "line12" "line13" "line14" "line15" "line16" "line17" "line18" "line19" "line20" %

$ cat test.txt | xargs -n1 -I @ echo -n '"@" '
"line1" "line2" "line3" "line4" "line5" "line6" "line7" "line8" "line9" "line10" "line11" "line12" "line13" "line14" "line15" "line16" "line17" "line18" "line19" "line20" %

上面涉及到了xargs的「-n」选项和「-I」选项,其选项含义如下:

-n max-args #最多读取max-lines行给command命令执行(默认是echo命令)
Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit.

-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.

-L max-lines #从非空输入中读取最多max-lines行给command命令执行(默认是echo命令)
Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x.

-P max-procs #并行模式
Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option with -P; otherwise chances are that only one exec will be done.

# Parallel sleep
$ time echo {1..5} | xargs -n 1 -P 5 sleep

real 0m5.013s
user 0m0.003s
sys 0m0.014s

# Sequential sleep
$ time echo {1..5} | xargs -n 1 sleep

real 0m15.022s
user 0m0.004s
sys 0m0.015s

通过一些例子来说明各个选项的作用:

$ cat test.txt | xargs -n2 # 和$(cat test.txt | xargs -L 2)命令等价
line1 line2
line3 line4
...
line19 line20

$ git log --format="%H %P" | xargs -L 1 git diff
参考链接:

=END=

, ,

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注