Shell中的xargs用法
xargs是给命令传递参数的一个过滤器, 也是组合多个命令的一个工具(有些命令无法通过管道,我们使用xargs来解决这个问题) xargs可以将管道或者标准输入(stdin)数据转换成命令行参数,也能够从文件的输出中读取数据 xargs 也可以将单行或多行文本输入转换为其他格式,例如多行变单行,单行补编多行 xargs 的输入将会包含换行和空白,不过通过xargs的处理,换行和空白将被空格取代 xargs是一个强有力的命令,它能够捕获一个命令的输出,然后传递给另外一个命令
[root@localhost xargs]# find /sbin -perm /0700
/sbin
[root@localhost xargs]# find /sbin -perm /0700 | ls -l
total 0
[root@localhost xargs]# find /sbin -perm /0700 | xargs \ls -l
lrwxrwxrwx. 1 root root 8 Jan 29 21:17 /sbin -> usr/sbin
[root@localhost xargs]#
xargs用于将混乱的字符单行输出(整理字符)
[root@localhost xargs]# 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
[root@localhost xargs]# 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
xargs -n用于多行输出(n后面的数字:表示每行有几个字符)
[root@localhost xargs]# cat test.txt | xargs -n3
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
-d是以什么为分隔符
[root@localhost xargs]# echo "nameXnameXnameXname" | xargs -dX
name name name name
[root@localhost xargs]# echo "nameXnameXnameXname" | xargs -dX -n2
name name
name name
一些命令如果不用xargs的话结合管道用不了(是一些配合管道)
[root@localhost xargs]#
[root@localhost xargs]# echo "noe two three" | mkdir
mkdir: missing operand
Try 'mkdir --help' for more information.
[root@localhost xargs]# echo "noe two three" |xargs mkdir
[root@localhost xargs]# ls
noe test.txt three two
-p询问用户是否执行该命令
[root@localhost xargs]# echo "one two three" | xargs -p touch
touch one two three ?...y
[root@localhost xargs]# ls
one test.txt three two
[root@localhost xargs]# echo "one two three" | xargs -p rm
rm one two three ?...
[root@localhost xargs]# ls
one test.txt three two
[root@localhost xargs]# echo "one two three" | xargs -p rm
rm one two three ?...y
[root@localhost xargs]# ls
test.txt
xargs -t不询问直接执行
[root@localhost xargs]# echo "one two three" | xargs -t touch
touch one two three
[root@localhost xargs]# ls
one test.txt three two
[root@localhost xargs]# echo "one two three" | xargs -t rm
rm one two three
[root@localhost xargs]# ls
test.txt
find /etc/ -type f -print0找出指定文件输出列表
find命令的 -print0 参数: 它指定输出的文件列表以none为分隔符
xagrs默认将空格作为分隔符,所以不适合处理文件名,因为文件名可能包含空格
xargs -0 的 -0参数
[root@localhost xargs]# find /etc/ -type f -print0 | xargs -0 ls
/etc/abrt/abrt-action-save-package-data.conf
/etc/abrt/abrt.conf
/etc/abrt/gpg_keys.conf
/etc/abrt/plugins/CCpp.conf
/etc/abrt/plugins/oops.conf
/etc/abrt/plugins/python.conf
/etc/abrt/plugins/vmcore.conf
/etc/abrt/plugins/xorg.conf
/etc/adjtime
/etc/aliases
……
xargs -I :-I 如果xargs将命令行参数传递给多个参数使用-I
-I 指定每一项命令行参数的代替字符
sh -c 执行多个命令
[root@localhost xargs]# sh -c "echo file;mkdir file"
file
[root@localhost xargs]# ls
file test.txt
[root@localhost xargs]# cat foo.txt
one
two
three
[root@localhost xargs]# cat foo.txt | xargs -I name sh -c 'echo name;mkdir name'
#这里的name就是one two three
one
two
three
[root@localhost xargs]# ls
foo.txt one test.txt three two
[root@localhost xargs]#
执行的时候就会代替掉命令中的name
Shell中的xargs用法
最新推荐文章于 2023-03-28 23:56:34 发布