异想天开

What's the true meaning of light, Could you tell me why

xargs命令

日期:2014-07-16 20:18:26
  
最后更新日期:2014-07-29 09:45:59
【技术文章,非码农勿入】
今天看人家用xargs的用法时,想到了xargs怎么提取文本文件一行行作为参数的方法。
[code lang="cpp"]
[root@test54vm8 test_dir]# man xargs
--max-args=max-args, -n max-args
Use at most max-args arguments per command line.
Fewer than max-args arguments will be used if the
size (see the -s option) is exceeded, unless the
-x option is given, in which case xargs will
exit.
--max-procs=max-procs, -P max-procs
Run up to max-procs processes at a time; the
default is 1. If max-procs is 0, xargs will run
as many processes as possible at a time. Use the
-n option with -P; otherwise chances are that
only one exec will be done.
[/code]
-P参数表示创建多少个进程来执行任务,默认为1,意思是可以并行化处理。-n表示每次最多读取行。 那么,可以这样:
[code lang="cpp"]
[root@test54vm8 test_dir]# cat aa.txt
aa
bb
cc
dd
ee
ff
[root@test54vm8 test_dir]# cat ./testa.sh
#!/bin/sh
echo " shell $1 input"
sleep 600
[root@test54vm8 test_dir]# cat aa.txt | xargs -n 1 -P 0 ./testa.sh
shell aa input
shell bb input
shell cc input
shell ee input
shell ff input
shell dd input
#打开另外一个终端
[root@test54vm8 ~]# ps -ef | grep testa
root 1603 23567 0 20:14 pts/0 00:00:00 xargs -n 1 -P 0 ./testa.sh
root 1604 1603 0 20:14 pts/0 00:00:00 /bin/sh ./testa.sh aa
root 1605 1603 0 20:14 pts/0 00:00:00 /bin/sh ./testa.sh bb
root 1607 1603 0 20:14 pts/0 00:00:00 /bin/sh ./testa.sh cc
root 1609 1603 0 20:14 pts/0 00:00:00 /bin/sh ./testa.sh dd
root 1611 1603 0 20:14 pts/0 00:00:00 /bin/sh ./testa.sh ee
root 1613 1603 0 20:14 pts/0 00:00:00 /bin/sh ./testa.sh ff
root 1620 1169 0 20:14 pts/1 00:00:00 grep --color=auto testa
[/code]
在testa.sh,加了睡眠的函数,防止程序执行完后,马上退出。可以看出xargs创建了6个进程在执行任务。