linux中xargs命令技巧的各种使用详解


本文摘自PHP中文网,作者黄舟,侵删。

xargs是给命令传递参数的一个过滤器,也是组合多个命令的一个工具。下面这篇文章主要给大家介绍了关于linux中xargs命令用法的相关资料,需要的朋友可以参考借鉴,下面来跟着小编一起看看吧。

前言

xargs命令是把接收到的数据重新格式化,再将其作为参数提供给其他命令,下面介绍xargs命令的各种使用技巧,一起来看看吧。

一、将多行输入转换成单行输入:

1

2

3

4

5

6

7

[root@host1 test]# echo -e "1 2 3 4 5 \n6 7 8 \n9 10 11 12" >example.txt

[root@host1 test]# cat example.txt

1 2 3 4 5

6 7 8

9 10 11 12

[root@host1 test]# cat example.txt |xargs

1 2 3 4 5 6 7 8 9 10 11 12

将单行输入转换成多行输出:

1

2

3

4

5

[root@host1 test]# cat example.txt | xargs -n 3

1 2 3

4 5 6

7 8 9

10 11 12

自定义定界符进行转换(默认的定界符是空格):

1

2

3

[root@host1 test]# echo "Hello:Hello:Hello:Hello" | xargs -d : -n 2

Hello Hello

Hello Hello

二、在脚本中运用:

1

2

3

[root@host1 test]# cat echo.sh

#!/bin/bash

echo $* '^-^'

当参数传递给echo.sh后,它会将这些参数打印出来,并且以"^-^"作为结尾:

1

2

3

4

5

6

[root@host1 test]# echo -e "Tom\nHarry\nJerry\nLucy" > args.txt

[root@host1 test]# cat args.txt | xargs bash echo.sh

Tom Harry Jerry Lucy ^-^

[root@host1 test]# cat args.txt | xargs -n 2 bash echo.sh

Tom Harry ^-^

Jerry Lucy ^-^

在上面的例子中,我们把参数源都放入args.txt文件,但是除了这些参数,我们还需要一些固定不变的参数,比如:

1

2

[root@host1 test]# bash echo.sh Welcome Tom

Welcome Tom ^-^

在上述命令执行过程中,Tom是变量,其余部分为常量,我们可以从"args.txt"中提取参数,并按照下面的方式提供给命令:

1

2

3

4

[root@host1 test]# bash echo.sh Welcome Tom

[root@host1 test]# bash echo.sh Welcome Herry

[root@host1 test]# bash echo.sh Welcome Jerry

[root@host1 test]# bash echo.sh Welcome Lucy

这时我们需要使用xargs中-I命令:

1

2

3

4

5

[root@host1 test]# cat args.txt | xargs -I {} bash echo.sh Welcome {}

Welcome Tom ^-^

Welcome Harry ^-^

Welcome Jerry ^-^

Welcome Lucy ^-^

-I {} 指定替换字符串,对于每一个命令参数,字符串{}都会被从stdin读取到的参数替换掉,

使用-I的时候,命令以循环的方式执行,如果有4个参数,那么命令就会连同{}一起被执行4次,在每一次执行中{}都会被替换为相应的参数。

三、结合find使用

xargs和find是一对非常好的组合,但是,我们通常是以一种错误的方式运用它们的,比如:

1

[root@host1 test]# find . -type f -name "*.txt" -print | xargs rm -f

这样做是有危险的,有时会删除不必删除的文件,如果文件名里包含有空格符(' '),则xargs很可能认为它们是定界符(例如,file text.txt会被xargs误认为file和text.txt)。

如果我们想把find的输出作为xargs的输入,就必须将-print0与find结合使用以字符null('\0')来分隔输出,用find找出所有.txt的文件,然后用xargs将这些文件删除:

1

[root@host1 test]# find . -type f -name "*.txt" -print0 | xargs -0 rm -f

这样就可以删除所有的.txt文件了,xargs -0 将\0作为输入定界符。

四、运用while语句和子shell

1

[root@host1 test]# cat files.txt | (while read arg ;do cat $arg;done)

这条命令等同于:

1

[root@host1 test]# cat files.txt | xargs -I {} cat {}

在while循环中,可以将cat $arg替换成任意数量的命令,这样我们就可以对同一个参数执行多条命令,也可以不借助管道,将输出传递给其他命令,这个技巧适应于多种问题场景。子shell操作符内部的多个命令可作为一个整体来运行。

总结

以上就是linux中xargs命令技巧的各种使用详解的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

Linux中如何查看机器是多少位

超线程和多线程的区别?

如何上传文件到Linux服务器

Linux下如何查看是否安装了apache服务

Linux怎么切换图形界面?

Linux操作系统如何在ecs上搭建docker

如何在Linux系统中利用node.js提取word及pdf文本内容的案例介绍

什么系统是基于Linux系统的

在控制台上如何将弹性网卡附加到时实例上

Linux中如何查找大文件?(代码示例)

更多相关阅读请进入《Linux》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...