文章目录
shell中常用的命令:xargs命令
1.xargs的功能
xargs存在的意义:
它能够捕捉一个命令的输出,然后传递给另外一个命令
由于很多命令不支持|管道来传递参数,而日常工作中有这个必要,所以就有了xargs命令
例如:
2.xargs的使用例子
替换工具 (读取输入数据 重写格式化后输出)
cat test.txt | xargs #规范文件中的内容
-n:指定每行字符数
cat test.txt | xargs -n4 #-n4指定每行4个字符
-d:指定分隔符
echo "hahaDhahaDhahaDhaha" | xargs -dD #指定字符D为分隔符
echo "hahaDhahaDhahaDhaha" | xargs -dD -n2 #指定每行2个字符
echo "hahaDhahaDhahaDhaha" | xargs -dD -n3
将标准输入转为命令行参数
echo "one two three four"
echo "one two three four" | mkdir
echo "one two three four" | xargs mkdir
ls
-p:询问用户是否执行命令
echo "one two three four" | xargs -p touch #-p询问是否执行指定动作
-t:不询问直接执行命令
echo "one two three four" | xargs -t rm #-t不询问 直接执行指定动作
与find命令结合使用
find /etc/ -type f -print0 | xargs -0 ls
Xargs默认将空格作为分隔符,所以不太能处理文件名,因为文件名可能包含空格。
find有一个参数print0, 指定输出文件列表以none分隔 。xargs命令的-0参数表示用none分割
-I:执行多条命令
sh -c "echo file;mkdir file" #sh -c 一次执行多个命令
vim 1.txt
cat 1.txt | xargs -I name sh -c 'echo name;mkdir name'
这里的name可以取任意名字,它指代的是1.txt里的内容