这里对LInux的sed命令进行简单的知识梳理,一方面为了巩固自己所学的知识,另一方面希望可以帮到其他正在学习Linux的小伙伴。
sed(英文:stream editor)流编辑器
可依照script的指令,来处理、编辑文本文件。其用途主要用以编辑一个或多个文件;简化对文件的反复操作;编写转换程序等。
语法
sed [-hnV] [-e<script>] [-f<script文件>] [文本文件]
参数
[-hnV]
- -h:显示帮助。
- -n:取消默认输出,显示script处理后的结果。
- -V:显示版本信息。
[-e<script>] :以选项中指定的script来处理输入的文本文件
- [-f<script文件>] :以选项中指定的script来处理输入的文本文件
动作
- p:打印,将将某选择的数据打印,通产与 sed -n 一起运行。
- s:查找替换,可以与g联合使用,表示对当前行进行全局匹配替换。
- d:删除,
- c:取代,c的后面可以接字符串,这些字符串可以取代n1,n2之间的行。
- a:新增,新增 字符串到当前行的 下一行
- i:插入,插入 字符串到当前行的 上一行。
问题:ac.txt 0-30的中 5-10的数字。
[root@Simile /]# sed -n '5,10'p ac.txt
5
6
7
8
9
10
‘s###g’实现全局替换 ,#是分隔符,理论上分隔符可以是任意分隔符,这里用#是个人习惯。若不加 -i 参数,则只是输出结果发生改变,不会修改文件的数据。
[root@Simile /]# echo The new line > cd.txt
[root@Simile /]# cat cd.txt
The new line
[root@Simile /]# sed ' s#line#string#g' cd.txt
The new string
[root@Simile /]# cat cd.txt
The new line
[root@Simile /]# sed -i ' s#line#string#g' cd.txt
[root@Simile /]# cat cd.txt
The new string
今天先写到这~不是很规范
(Simile:如果文中的内容出现遗漏和偏差,博主会第一时间进行更新再发布,感谢大家的支持和理解~)
跟着老男孩坐了一个题目
把/test目录及其子目录下的所有以扩展名.sh结尾的文件中,包含 Simile 的字符串全部替换成 NewLine。
方法一
第一步:建立测试数据。
使用 mkdir 命令 创建 /test 目录及其子目录 demo
[root@Simile /]# mkdir -p /test/demo
使用 echo 命令在4个不同文件名后缀为.sh的文件中,写入相同数据 Simile
[root@Simile test]# echo "Simile" > demo/a.sh
[root@Simile test]# echo "Simile" > b.sh
[root@Simile test]# echo "Simile" > c.sh
[root@Simile test]# echo "Simile" > .sh
第二步:查找 并 查看数据
使用 find 命令,查看/test目录及其子目录下的四个.sh后缀的文件数据
[root@Simile test]# find /test -type f -name "*.sh"
/test/b.sh
/test/c.sh
/test/.sh
/test/demo/a.sh
使用 find 命令并结合管道 xargs,使用 cat 命令查看数据
[root@Simile test]# find /test -type f -name "*.sh" |xargs cat
Simile
Simile
Simile
Simile
第三部:尝试修改输出,最终替换数据
使用 find 命令并结合管道 xargs ,再依靠 sed s###g修改输出
[root@Simile test]# find /test -type f -name "*.sh" |xargs sed 's#Simile#Newline#g'
Newline
Newline
Newline
Newline
[root@Simile test]# find /test -type f -name "*.sh" |xargs cat
Simile
Simile
Simile
Simile
使用sed -i 参数,最终替换数据,完成任务
[root@Simile test]# find /test -type f -name "*.sh" |xargs sed -i 's#Simile#Newline#g'
[root@Simile test]# find /test -type f -name "*.sh" |xargs cat
Newline
Newline
Newline
Newline
方法二
注意的是 这里的find部分用使用 Tab 按键上的反引号进行标注
[root@Simile test]# sed -i 's#Newline#Simile#g' `find /test -type f -name "*.sh"`
[root@Simile test]# find /test -type f -name "*.sh" |xargs cat
Simile
Simile
Simile
Simile