shell中常用的命令—xargs命令
1.xargs的功能
- xargs是给命令传递参数的一个过滤器,也是组合多个命令的一个工具
- xargs可以将管道或标准输入数据转换成命令行参数,也能够从文件的输出中读取数据
- xargs也可以将单行或多行文本输入转换为其他格式(多行变单行,单行变多行)
- xargs默认的命令是echo,这以为这通过管道传递给xargs的输入将会包含换行和空白,不过通过xargs的处理,换行和空白将被空格取代
xargs存在的意义:
它能够捕捉一个命令的输出,然后传递给另外一个命令
由于很多命令不支持|管道来传递参数,而日常工作中有这个必要,所以就有了xargs命令
例如:
2.xargs的使用
例1:
cat test.txt | xargs #规范文件中的内容
cat test.txt | xargs -n4 #-n4指定每行4个字符
例2:
echo "hahaDhahaDhahaDhaha" | xargs -dD #删除字符D
echo "hahaDhahaDhahaDhaha" | xargs -dD -n2 #指定每行2个字符
echo "hahaDhahaDhahaDhaha" | xargs -dD -n3
例3:
echo "one two three four"
echo "one two three four" | mkdir
echo "one two three four" | xargs mkdir
ls
例4:
[root@node2 xargs]# echo "one two three four" | xargs -p touch #-p询问是否执行指定动作
touch one two three four ?... #不输入yes就不会执行
[root@node2 xargs]# ls
test.txt
[root@node2 xargs]# echo "one two three four" | xargs -p touch
touch one two three four ?...yes #输入yes才会执行
[root@node2 xargs]# ls
four one test.txt three two
[root@node2 xargs]# echo "one two three four" | xargs -t rm #-t不询问 直接执行指定动作
ls
例5:
find /etc/ -type f -print0 | xargs -0 ls
sh -c "echo filel;mkdir file"
ls
rm -fr file
vim 1.txt
cat 1.txt | xargs -I name sh -c 'echo name;mkdir name'
ls