shell命令linux

xargs命令详解

2019-11-23  本文已影响0人  洛丽塔的云裳

原理详见 https://www.cnblogs.com/f-ck-need-u/p/5925923.html

0. xargs概述:

whereis xargs : #二进制文件、源、使用手册位置

xargs: /usr/bin/xargs /home/xxx/sbin/xargs /home/work/xxx/bin/xargs /usr/share/man/man1p/xargs.1p.gz /usr/share/man/man1/xargs.1.gz

whatis xargs : # xargs所在使用手册的章节位置

xargs       (1)  - build and execute command lines from standard input

man xargs : # xargs所在使用手册的章节位置

xargs是一个强有力的命令,它能够捕获一个命令的输出,然后传递给另外一个命令。

命令格式:

somecommand | xargs -item command

1. 为什么要用xargs?

有些时候我们需要对一些linux操作进行处理,比如

现在想要kill这个进程。使用ps -ef|grep pc_driver| kill 管道是不可行的,


换个方法,使用如下命令,其效果类似 kill $PID

kill `ps -ef|grep pc_driver`

2. xargs和管道的区别?

2. xargs的常用操作命令

-a 选项: 处理文本
-n 选项: 将数据按照(-n 后的数字)分组, 默认按照空格划分
-d 选项: 分隔符,默认的xargs分隔符是回车
-t 选项: 在每次执行xargs后面的命令都会先打印一遍命令后才正式执行
-p 选项: 交互式处理
-E 选项: 传递终止符。注-E只有在xargs不指定-d的时候有效,如果指定了-d则不起作用,而不管-d指定的是什么字符,空格也不行

测试txt内容如下

1, 2, 3, 4, 5, 6, 7, 8, 9
a, b, c, d, e, f, g, h, i

(1) 执行 cat test.txt | xargs,或者 cat test.txt | xargs -a test.txt测试结果

1, 2, 3, 4, 5, 6, 7, 8, 9 a, b, c, d, e, f, g, h, i

(2) 执行 cat test.txt | xargs -n 3, 测试结果

1, 2, 3,
4, 5, 6,
7, 8, 9
a, b, c,
d, e, f,
g, h, i

(3) 执行cat test.txt | xargs -d ",", 测试结果

1  2  3  4  5  6  7  8  9
a  b  c  d  e  f  g  h  i

(4) 执行cat test.txt | xargs -n 3 -t, 测试结果

/bin/echo 1, 2, 3,
1, 2, 3,
/bin/echo 4, 5, 6,
4, 5, 6,
/bin/echo 7, 8, 9
7, 8, 9
/bin/echo a, b, c,
a, b, c,
/bin/echo d, e, f,
d, e, f,
/bin/echo g, h, i
g, h, i

(4) 执行cat test.txt | xargs -n 3 -p, 测试结果


(5) 执行echo 'a b c' | xargs -E 'c' echo, 测试结果
上一篇下一篇

猜你喜欢

热点阅读