使用xargs要特别注意,默认情况下,它是以整行作为[项]的.

-a

指定文件来代替标准输入(stdin).

➜  xargs  cat hello.txt
a b c d
➜  xargs  xargs -a hello.txt
a b c d
➜  xargs

–null 或者 -0

*输入项*,是以null字符结尾的,而不是以白空格(whitespace),引号,反斜杠等(这时,会将这些当作字面值处理)。

例子:

➜  xargs  echo "hello // world" | xargs -n 2
hello //
world
➜  xargs  echo "hello // world" | xargs -0 -n 2
hello // world

➜  xargs

-d 或者 –delimiter=delim

输入项以指定*字符*作为结束.(注意,不支持多字符),例如:

➜  xargs  echo "hello//world" | xargs -d "/" -n 1
hello

world

➜  xargs

-E eof-str 或者 –eof=eof-str 或者 -e[eof-str]

设置文件结束字符串.

➜  xargs  echo "hello//world hello//word2" | xargs -E "world" -n 1
hello//world
hello//word2
➜  xargs

-I replace-str 或者 –replace=replace-str 或者 -i[replace-str]

按行输入的内容替换到指定的replace-str中.例如:

➜  xargs  cat hello.txt| xargs -I XYZ echo -e "line content: XYZ\nAgain: XYZ"
line content: a b c d
Again: a b c d
line content: aa bb cc dd
Again: aa bb cc dd
➜  xargs

-L 1

-L max-lines 或者 –max-lines=[max-lines] 或者 –l[max-lines]

将最多max-lines行的输入当成一行。例如:

➜  xargs  cat hello.txt
a b c d
aa bb cc dd
➜  xargs  cat hello.txt | xargs -L 1 echo
a b c d
aa bb cc dd
➜  xargs  cat hello.txt | xargs -L 2 echo
a b c d aa bb cc dd
➜  xargs

–max-args=max-args 或者 -n max-args

每个命令行最多使用max-args个参数。默认情况下,xargs会一次性传递所有数据,当作一个参数。使用这个参数,可以覆盖默认的行为。

➜  xargs  cat hello.txt | xargs -L 2 -n 3 echo
a b c
d aa bb
cc dd
➜  xargs

-t

执行之前,打印一下要执行的命令

–show-limits

显示命令行长度的限制.(字节)

–exit 或者 -x

退出,如果超出-s参数指定的值.(字节)

–max-procs=max-procs 或者 -P max-procs

一次运行max-procs个进程。默认为1,如果设置为0,则xargs会尽可能在同一时间同时运行多个进程。

示例

删除redis某些指定的key

redis-cli -h 10.0.0.5 -n 2 -p 6579 -a yourpasswd keys *session* | xargs redis-cli -n 2 -h 10.0.0.5 -p 6579 -a yourpasswd del

根据文件里指定的key-value来设置redis

➜  xargs  cat k-v.txt
key1 value1 key2 value2 key3 value3
➜  xargs

➜  xargs  cat k-v.txt
key1 value1 key2 value2 key3 value3
➜  xargs  cat k-v.txt | xargs -P 0 -n 2  redis-cli -p 6379 set
OK
OK
OK
➜  xargs

删除由文件里指定的redis的key

一个一个删除:

➜  xargs  cat redis.txt
key1 key2 key3 key4
➜  xargs

➜  xargs  cat redis.txt | xargs -P 0 -n 1  redis-cli -p 6379 del
(integer) 1
(integer) 1
(integer) 1
➜  xargs

一次性删除:

➜  xargs  cat redis.txt
key1 key2 key3 key4
➜  xargs

➜  xargs  cat redis.txt | xargs -P 0 redis-cli -p 6379 del
(integer) 3
➜  xargs