总体而言,sed命令可以对文本进行查找、删除、插入、替换等操作。它跟vim或者vi命令最大的去区别是,后者只能通过人工交互的方式,对文本进行处理。而很多时候,我们希望脚本自动化的进行文本处理,那么sed无疑是我们的好帮手
sed OPTIONS [SCRIPT] [INPUTFILE...]
-i
,-n
,后续会详解echo "Welcome To The Geek Stuff" | sed 's/\(\b[A-Z]\)/\(\1\)/g'
为了方便对命令处理效果的说明,首先我们准备一个文本sed_learn.txt
,其内容如下
unix is great os. unix is opensource. unix is free os.
learn operating system.
unix linux which one you choose.
在script中,以p
做为查找输出命令,意即print
打印1到2行的文本
sed -n '1,2 p' sed_learn.txt
输出结果
unix is great os. unix is opensource. unix is free os.
learn operating system.
上述搜索打印使用到了参数-n
,详细讲解
打印包含unix
关键字的行sed -n '/unix/p' sed_learn.txt
,输出结果如下
unix is great os. unix is opensource. unix is free os.
unix linux which one you choose.
其中两斜杠/unix/
中间,除了可以指定关键字,还可以指定正则表达式
使用G
表示插入空行
sed 'G' sed_learn.txt
结果如下
unix is great os. unix is opensource. unix is free os.
learn operating system.
unix linux which one you choose.
sed 'G;G' sed_learn.txt
unix is great os. unix is opensource. unix is free os.
learn operating system.
unix linux which one you choose.
sed '/love/G' sed_learn.txt
表示在包含love
的行后面插入新行sed 's/^/ /' a.txt
表示在所有行前,插入5个空格,^
表示行首在script中指定d
命令,表示对文本进行相关的删除动作
比如sed '1d' sed_learn.txt
表示删除第一行
sed '1,2d' sed_learn.txt //表示删除1到2行
sed '1,$d' sed_learn.txt //表示删除1到最后一行
sed '$d' sed_learn.txt
sed '/unix/d' sed_learn.txt //表示删除所有包含unix的行
sed '/^$/d' sed_learn.txt
替换命令的脚本格式一般为sed line_number1,line_number2 's/search_keyword_or_regular_express/string_for_replace/search_range_for_one_line'
sed '1,3 s/unix/linux/' sed_learn.txt
表示,将1到3行中的第一次匹配到unix的地方,替换成linuxsed '1,3 s/unix/linux/g' sed_learn.txt
表示,将1到3行中的所有匹配到unix的地方,替换成linuxsed = sed_learn.txt | sed 'N;s/\n/\t/'
, 其中等号=
是给文本每行前面插入一个带数字的行,由于换行了,所以管道符后面将换行符\n
变成了制表符\t
。 当然我们可以直接换成空格sed = sed_learn.txt | sed 'N;s/\n/ /
sed '/./=' a.txt | sed '/./N; s/\n/ /'
,通过/./
匹配到所有非空的行,然后使用=
编号。最后,再将换行符\n
替换成空格在script中,可以指定多组命令,用分号隔开就行
比如sed 'G' sed_learn.txt
,表示插入一个空行
而sed 'G;G' sed_learn.txt
表示插入两个空行
-i
前面讲的所有查询、删除、替换,都是直接将处理结果输出到终端,为了保留这些处理结果,我们可以使用重定向到某个文件进行保存,比如sed '/unix/d' sed_learn.txt > result.txt
。但我们也可以通过指定-i
参数,直接将修改后的结果,更新到原文件,这里的-i
代表in place
即为就地
的意思
例如sed -i '1,$ s/unix/linux/g' sed_learn.txt
会将sed_learn.txt的内容,直接更新为如下
linux is great os. linux is opensource. linux is free os.
learn operating system.
linux linux which one you choose.
-n
默认情况下,p
指令会将所有文本打印出来,并将匹配到文本进行重复打印。
比如执行sed '1,2 p' sed_learn.txt
, 其结果如下,
unix is great os. unix is opensource. unix is free os.
unix is great os. unix is opensource. unix is free os.
learn operating system.
learn operating system.
unix linux which one you choose.
可以看到,它不光把第三行的内容也输出了,还把1,2行进行了重复打印。而-n
则可以只打印匹配到的内容,且不重复
基本上,sed命令,都是先定位到某行,或某行的某个位置,然后进行相应的处理。除此之外,还需要指定具体要对那些行进行前述处理
https://www.geeksforgeeks.org/sed-command-in-linux-unix-with-examples/
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.cnblogs.com/niceshot/p/15644895.html
内容来源于网络,如有侵权,请联系作者删除!