
Unix命令都带有参数,有些命令可以接受”标准输入(stdin)”作为参数。而管道命令(|)的作用,是将左侧命令的标准输出转换为标准输入,提供给右侧命令作为参数使用。虽然,在 Unix 系统中大多数命令都不接受标准输入作为参数,只能直接在命令行输入参数,这导致无法用管道命令传递参数。比如,我们日常使用的 echo 命令就不接受管道传参。而 xargs 命令的作用,就是将标准输入转为命令行参数。
# grep命令接受管道传参
> cat /etc/passwd | grep root
# echo命令不接受管道传参
> echo "hello rumenz" | echo
# 将标准输入转为命令行参数
> echo "hello rumenz" | xargs echo
hello rumenz-d指定分隔符,默认使用空格分割# 空格作为分隔符
$ echo "one two three" | xargs mkdir
# 指定制表符\t作为分隔符
$ echo -e "a\tb\tc" | xargs -d "\t" echo
a b c-p 打印出要执行的命令并询问用户是否要执行> echo 'one two three' | xargs -p touch
touch one tow three ?...y-0 表示用 null 当作分隔符find命令有一个特别的参数-print0,用来指定输出的文件列表以null作为分隔符
> find /path -type f -print0 | xargs -0 rm> xargs -L 1 find -name
"*.txt"
./1.txt
./rumenz.txt
./2.txt
./3.txt-n指定每次将多少项作为命令行参数> echo {0..9} | xargs -n 2 echo # 将命令行参数传给多个命令
> cat foo.txt
one
two
three
> cat foo.txt | xargs -I {} sh -c 'echo {}; mkdir {}'
one
two
three
> ls
one two three> cat rumenz.txt
1 2 3 4
5 6
7 8 9
> cat rumenz.txt | xargs
1 2 3 4 5 6 7 8 9> cat rumenz.txt
1 2 3 4 5 6 7 8 9
> cat rumenz.txt | xargs -n 3
1 2 3
4 5 6
7 8 9> echo "rumenz:123:rumenz:456:rumenz:789" | xargs -d : -n 2
rumenz 123
rumenz 456
rumenz 789> find . -type f -name "*.txt" -print | xargs rm -f> cat rumenz.txt | xargs wget -c原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。