xargs, sed,grep 组合使用

本文深入解析了xargs和sed命令的高级用法,包括如何利用xargs处理多个输出,以及sed如何编辑和处理文本文件。通过实例展示了xargs的-n和-I选项,以及sed的-n,'p','i','a'等命令的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

xargs

xargs可以捕获一个命令的输出,然后传递给另外的一个命令。

例如

find /bin -name bash | xargs ls -al
-rwxr-xr-x 1 root root 1113504 Jun  7  2019 /bin/bash

find /bin -name bash 的输出传递给ls -al
上面的例子中find /bin -name bash 只有一个输出,直接传递给ls -al。
若前面的命令有多个输出,挨个将输出传递给xargs后面的命令;假若xargs后面无命令,则xargs对前面命令的输出,重新格式化后输出。

test.txt文件存储以下数据,直接输出如下:

cat test.txt
123    234                   345

将输出结果传递给xargs,对内容进行格式化后输出

cat test.txt | xargs
123 234 345

xargs 选项

-n num 后面加次数,表示命令在执行的时候一次用的argument的个数,默认是用所有的。

获取输出的执行行,可以通过-n 1 选项将输出逐行打出

cat test.txt | xargs -n1
123
234
345

xargs参数处理

xargs 的一个选项 -I,使用 -I 指定一个替换字符串 {},这个字符串在 xargs 扩展时会被替换掉,当 -I 与 xargs 结合使用,每一个参数命令都会被执行一次,复制所有图片文件到 /data/images 目录下:

ls *.jpg | xargs -n1 -I {} cp {} /data/images

sed

sed 可依照脚本的指令来处理、编辑文本文件

使用sed选择指定行,例如选择第二行 '2,2p'

cat test.txt | xargs -n1 | sed -n '2p'
234

grep + xargs + sed 替换文件中的字符串

通过grep xargs sed进行组合,将当前文件夹下所有的test1 替换为test2

grep -rl "test1" ./ | xargs sed -i 's/test1/test2/g'

grep 参数解读

-r, --recursive
Read all files under each directory, recursively, following symbolic links only if they are on the command line.  Note that if no file operand is given, grep searches the working directory.  This is equivalent to the -d recurse option.
-l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed.  The scanning will stop on the first match.

sed 参数解读 todo

-i 

grep + xargs + sed 在某行前/后插入指定字符

在test2上一行添加test1

grep -rl "test2" ./ | xargs sed -i '/test2/itest1'
grep -rl "test2" ./ | xargs sed -i '/test2/i\ \ \ \ test1' # test1 前添加四个空格

在test2下一行添加test3

grep -rl "test2" ./ | xargs sed -i '/test2/atest3'
a
text   Append text, which has each embedded newline preceded by a backslash.
i
text   Insert text, which has each embedded newline preceded by a backslash.

参考
[1] https://blog.youkuaiyun.com/u011304615/article/details/71450847

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值