专业编程基础技术教程

网站首页 > 基础教程 正文

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

ccvgpt 2024-07-28 12:18:35 基础教程 6 ℃

xargs命令

xargs

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

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

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

xargs命令参数

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

案例代码

案例1:

#!/bin/bash

# xargs命令,将标准输入转为命令行参数
echo "hello world" | xargs echo
echo ..

# 写入文件
cat > words.txt <<'EOF'
张天师祈禳瘟疫 洪太尉误走妖魔
王教头死走延安府 九纹龙大闹史家村
史大郎夜走华阴县 鲁提辖拳打镇关西
赵员外重修文殊院 鲁智深大闹五台山
小霸王醉入销金帐 花和尚大闹桃花村
EOF

# 多行变单行
cat words.txt |xargs
echo ..
cat words.txt |xargs > words_one.txt

# 单行变多行
cat words_one.txt |xargs -n3
echo ..

# -d参数,更改分隔符为空格
echo -e "张天师,洪太尉,王教头,史大郎,鲁提辖,赵员外,小霸王" | xargs -d "," echo
echo ..
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 rm
echo ..

# 批量创建文件
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.gz
echo ..
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*" -print0
echo ""
echo ..
find ./ -type f -name "file*" -print0 | xargs -0 rm -f
echo ..

# 从检索到的文件中查找包含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 <<-EOF
file1
file2
file3
file4
EOF

# 根据文件内容,打印并创建目录
# -I,每一项命令行参数的替代字符串
cat 1.txt | xargs -I item sh -c 'echo item; touch item'
echo ..

# 打印
find ./ -type 'f' -name "file*"

Tags:

最近发表
标签列表