1.将多行换成转换成单行

  1. [root@CentOS5 shell]# cat a.txt
  2. hello world
  3. oh my god
  4. [root@CentOS5 shell]# cat a.txt | xargs
  5. hello world oh my god
2.将单行换成多行

  1. [root@CentOS5 shell]# cat a.txt
  2. hello world
  3. oh my god
  4. [root@CentOS5 shell]# cat a.txt | xargs -n 1
  5. hello
  6. world
  7. oh
  8. my
  9. god
  10. [root@CentOS5 shell]# cat a.txt | xargs -n 2
  11. hello world
  12. oh my
  13. god

3.分割字符串

  1. [root@CentOS5 shell]# echo "123;abc;xyz;456"| xargs -d ';'
  2. 123 abc xyz 456
  3. [root@CentOS5 shell]# echo "123;abc;xyz;456"| xargs -d ';' -n 1
  4. 123
  5. abc
  6. xyz
  7. 456
上面这个当然也可以通过awk来分割字符串

  1. [root@CentOS5 shell]# echo "123;abc;xyz;456"| awk -F ';' 'END{for(i=1;i<=NF;i++)print $i}'
  2. 123
  3. abc
  4. xyz
  5. 456
或者通过sed来也可以实现替换字符串,相对比 xargs就稍多敲点命令啦

  1. [root@CentOS5 shell]# echo "123;abc;xyz;456"| sed 's/;/\n/g'
  2. 123
  3. abc
  4. xyz
  5. 456

4.通过xargs批量传参
如,批量创建文件

  1. [root@CentOS5 shell]# ls
  2. a.txt
  3. [root@CentOS5 shell]# cat a.txt
  4. hello
  5. world
  6. oh
  7. my
  8. god
  9. [root@CentOS5 shell]# cat a.txt | xargs touch
  10. [root@CentOS5 shell]# ls
  11. a.txt god hello my oh world
接上批量删除文件

  1. [root@CentOS5 shell]# cat a.txt | xargs rm -f
  2. [root@CentOS5 shell]# ls
  3. a.txt
但如果我想 创建“god.log  hello.log  my.log  oh.log  world.log” 这样的文件怎么办呢?
xargs 中有个-I选项 可以通过 -I {} 来代表输入参数,如下:


  1. [root@CentOS5 shell]# cat a.txt
  2. hello
  3. world
  4. oh
  5. my
  6. god
  7. [root@CentOS5 shell]# ls
  8. a.txt
  9. [root@CentOS5 shell]# cat a.txt | xargs -I {} touch {}.log
  10. [root@CentOS5 shell]# ls
  11. a.txt god.log hello.log my.log oh.log world.log






10-16 07:44
查看更多