今天,我们来学习一下Linux中非常重要的命令参数过滤器:xargs !
xargs : 给其后续命令传递参数的过滤器;处理管道或stdin的输入,将其转换为命令参数;其默认命令为echo,默认分隔符为空格。
用途:
1,用于组合多个命令,构成单行命令;
比如,ls命令不支持管道,但可通过xargs命令传递参数;
2,避免命令输入的参数过长;
可使用-n选项给参数分组,从而避免参数过长;
选项:
- -o 将管道中的特殊字符还原成一般字符;
- -e
STRING
此选项意译为EOF,即End Of File,选项后紧跟一个字符串STRING,当xargs分析到STRING时,就结束分析; - -p 操作时进行交互式询问;
- -n# 命令执行时,一次处理#个参数;
- -d
CHAR
紧跟CHAR,指定分隔符为CHAR; - I
STRING
用xargs转换的参数替换下一命令中出现的字符串STRING;
用法详解:
我们以test.txt作为测试文件来演示。
[root@localhost jeffrey]# cat test.txt
a b c d e f g
h i j k l m n
o p q r s t u
v w x y z
(1)单独使用,将管道或标准输入转换为一行参数,以空格为分隔符;
[root@localhost jeffrey]# cat test.txt | xargs
a b c d e f g h i j k l m n o p q r s t u v w x y z
(2)使用选项-e设置j
为处理结束符;
[root@localhost jeffrey]# cat test.txt | xargs -ej
a b c d e f g h i
(3)使用选项-p,操作时进行询问;
[root@localhost jeffrey]# cat test.txt | xargs -p
echo a b c d e f g h i j k l m n o p q r s t u v w x y z ?...y
a b c d e f g h i j k l m n o p q r s t u v w x y z
(4)使用选项-n,命令执行时一次处理#个参数;一次处理4个参数,所以4个参数为一行;
[root@localhost jeffrey]# cat test.txt | xargs -n4
a b c d
e f g h
i j k l
m n o p
q r s t
u v w x
y z
(5)使用-d选项,设置分隔符为:
;
[root@localhost jeffrey]# echo "cherry:Jeffrey:Darry:Karry" | xargs -d:
cherry Jeffrey Darry Karry
(6)使用-I选项,用参数替换下一命令中出现的STRING;查看所有以.txt结尾的文件,并删除之。
[root@localhost jeffrey]# ls *.txt
Jeffrey.txt lovers.txt save.txt test.txt Tom.txt
[root@localhost jeffrey]# ls *.txt | xargs -I '{}' rm {}
(7)使用-0选项,处理文件名中的特殊字符;
有时,我们的文件名中会出现空格,但是xargs以空格或换行符作为分隔符,所以会出现问题:hello hello.txt
为一个文件,但是xargs却将其转换成两个参数;这是因为xargs将文件命令中的空格当成了分隔符;
[root@localhost jeffrey]# find -name 'hello hello.txt' -print | xargs -n1
./hello
hello.txt
因此,我们使用-0选项,将空格视为一般字符,而不是分隔符;
[root@localhost jeffrey]# find -name 'hello hello.txt' -print0 | xargs -n1 -0
./hello hello.txt