我是靠谱客的博主 机智高跟鞋,最近开发中收集的这篇文章主要介绍xargs, sed,grep 组合使用,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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.csdn.net/u011304615/article/details/71450847

最后

以上就是机智高跟鞋为你收集整理的xargs, sed,grep 组合使用的全部内容,希望文章能够帮你解决xargs, sed,grep 组合使用所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(49)

评论列表共有 0 条评论

立即
投稿
返回
顶部