xargs命令xargs xargs,标准输入转为命令行参数,extended arguments,给命令传递参数的一个过滤器,也是组合多个命令的一个工具; xargs,读取标准输入和管道中的数据,用于弥补命令不能从管道中读取数据的不足。 xargs命令参数 -n, 指定一次读取几个参数;-d, 可以更改分隔符;-p, 打印出要执行的命令;-t, 打印出最终要执行的命令,直接执行;-0, 数字零 用NULL当作分隔符;-L, 指定多少行作为一个命令行参数;-I, 指定每一项命令行参数的替代字符串;--max-procs, 指定同时用多少个进程并行执行命令,max-procs被指定为0,xargs 将会尽可能的运行多个进程;
案例代码案例1: #!/bin/bash# xargs命令,将标准输入转为命令行参数echo 'hello world' | xargs echoecho ..# 写入文件cat > words.txt <<'EOF'张天师祈禳瘟疫 洪太尉误走妖魔王教头死走延安府 九纹龙大闹史家村史大郎夜走华阴县 鲁提辖拳打镇关西赵员外重修文殊院 鲁智深大闹五台山小霸王醉入销金帐 花和尚大闹桃花村EOF# 多行变单行cat words.txt |xargsecho ..cat words.txt |xargs > words_one.txt# 单行变多行cat words_one.txt |xargs -n3echo ..# -d参数,更改分隔符为空格echo -e '张天师,洪太尉,王教头,史大郎,鲁提辖,赵员外,小霸王' | xargs -d ',' echoecho ..echo '张天师,洪太尉,王教头,史大郎,鲁提辖,赵员外,小霸王' | xargs -d ',' echo 案例2:
案例3: #!/bin/bash# 生成文件cat /etc/passwd > passwd.txt# 批量创建文件echo 'file1 file2 file3 file4 file5 file6' | xargs touch# -0参数与find命令find ./ -type f -name 'file*' -print0echo ''echo ..find ./ -type f -name 'file*' -print0 | xargs -0 rm -fecho ..# 从检索到的文件中查找包含root的行# find . -type 'f' -name '*.txt' | xargs grep 'root'find . -type 'f' -name '*.txt' | xargs grep -n 'root'echo ..# -L参数,# 进入交互式# xargs -L 1 find -name# 写入文件内容cat > 1.txt <<-EOFfile1file2file3file4EOF# 根据文件内容,打印并创建目录# -I,每一项命令行参数的替代字符串cat 1.txt | xargs -I item sh -c 'echo item; touch item'echo ..# 打印find ./ -type 'f' -name 'file*' |
|
来自: lifebegins40s > 《linux》