分享

Linux,shell,xargs命令,标准输入转为命令行参数,代码案例

 lifebegins40s 2022-12-14 发布于广东

xargs命令

xargs

xargs,标准输入转为命令行参数,extended arguments,给命令传递参数的一个过滤器,也是组合多个命令的一个工具;

xargs,读取标准输入和管道中的数据,用于弥补命令不能从管道中读取数据的不足。

xargs命令参数

-n, 指定一次读取几个参数;-d, 可以更改分隔符;-p, 打印出要执行的命令;-t, 打印出最终要执行的命令,直接执行;-0, 数字零 用NULL当作分隔符;-L, 指定多少行作为一个命令行参数;-I, 指定每一项命令行参数的替代字符串;--max-procs, 指定同时用多少个进程并行执行命令,max-procs被指定为0,xargs 将会尽可能的运行多个进程;
man xargs# 查看版本xargs --version# 帮助xargs --help#type xargswhich xargswhereis 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:

#!/bin/bash# 批量创建文件echo 'file1 file2 file3 file4 file5 file6' | xargs touch# -p参数,打印出要执行的命令# echo 'file1 file2 file3 file4 file5 file6' | xargs -p touch# -t参数,打印出最终要执行的命令,然后直接执行echo 'file1 file2 file3 file4 file5 file6' | xargs -t rmecho ..# 批量创建文件echo 'file1 file2 file3 file4 file5 file6' | xargs touch# 查找文件find ./ -type f -name 'file*'echo ..# 查找到文件并删除find ./ -name 'file*' | xargs rm -f# find ./ -name 'file*' | xargs -p rm -f# 查找到文件find ./ -type f -name '*.txt'echo ..# 查找到文件并打包find ./ -type f -name '*.txt' | xargs tar zcvf my.tar.gz# -p参数,打印出要执行的命令# find ./ -type f -name '*.txt' | xargs -p tar zcvf my.tar.gzecho ..ls -l my.tar.gz

案例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*'

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多