Linux|常用命令|sed

Linux|常用命令|sed
文章图片

【Linux|常用命令|sed】
目录

  • SED的适用场景
  • Option
  • Action作用的行范围
  • Action类型:行的增删改查
  • 正则Regular Expression

SED的适用场景
SED是Stream EDitor的简称,也就是流编辑器,适用在不打开文件的情况下,增删改查文件内容
SED command in UNIX stands for stream editor and it can perform lots of functions on file like searching, substitution or find and replace, insertion or deletion.By using SED you can edit files even without opening them, which is much quicker way to find and replace something in file, than first opening that file in VI Editor and then changing it.
语法格式
#第一种语法格式 STDOUT | sed [option] #第二种语法格式 sed [option] sed [option] <

command使用双引号包裹,变量生效
command使用单引号包裹,单引号包裹变量后生效
command建议使用单引号包裹,避免非变量生效,如sed '$d'sed "$d"
== <[area] action>
Option
参数说明
-n #常和p搭配 -e #-e -e -f #读取文件中的 -i #更新文件(默认是输出到STDOUT) -r #使用扩展正则表达式,建议使用,语法便利

命令的执行顺序对结果有影响
sed -e -e $file
sed 'command; command' $file
sed $file | sed $file
Action作用的行范围
范围 示例
缺省默认所有行
n1 command 第n行
$ command 尾行
n1,n2 command 第n1~n2行
n1,+n 第n1~n1+n行
/ptn1/ command 所有匹配到的行
/ptn1/,/ptn2/ command ptn=ptn1,匹配则区间开始,ptn=ptn2,匹配则区间结束,闭区间,反复执行
/ptn1/,+n command 匹配ptn1即随后n行,反复执行
n1,/ptn2/ command 从n1行到匹配ptn2的闭区间,以及后续匹配ptn2的所有行
/ptn1/,n2 command 从匹配ptn1到n2行的闭区间,以及后续匹配ptn1的所有行
Action类型:行的增删改查
p print
i insert
a append
r read
w write
c
s
y
d
#目标行后新增行 sed -r '[area] a ' $file #目标行前新增行 sed -r '[area] i ' $file #目标行后新增多行,方式一,单引号包裹command sed -r '[area] a \ \ ' $file #目标行后新增多行,方式二,双引号包裹command sed -r "[area] a \n\n" $file #复制目标行 sed -r "[area] p" $file

sed -r '[area] d'

#定界符,定界符出现在样式内部时,需要进行转义 echo -e … | sed -r '[area] s/origin/new/' $file echo -e … | sed -r '[area] s|origin|new|' $file echo -e … | sed -r '[area] s:origin:new:' $file#每行只替换第一个匹配的字符串 echo -e … | sed -r '[area] s/origin/new/' $file echo -e … | sed -r '[area] s/origin/new/1' $file#每行替换所有匹配的字符串 echo -e … | sed -r '[area] s/origin/new/g' $file#每行替换第n个及后续匹配的字符串 echo -e … | sed -r '[area] s/origin/new/ng' $file#匹配忽略大小写 echo -e … | sed -r '[area] s/origin/new/ngi' $file#匹配和反向引用,&代表匹配的部分 sed -r '[area] s/pattern/prefix&/g' $file #目标字符串前添加字符串 sed -r '[area] s/pattern/&postfix/g' $file #目标字符串后添加字符串 sed -r '[area] s/^/prefix&/g' $file #在所有行首添加 sed -r '[area] s/$/&postfix/g' $file #在所有行末添加 #分组(匹配的一部分)和反向引用 sed -rn '[area] s/.*(ptn1).*(ptn2).*/\1\2/ p' $file #分组(匹配的一部分)和反向引用,提取字符串 sed -rn '[area] s/.*(ptn1).*/\1/ p' $file#将多行替换成一行 sed '[area] c new line' $file

sed -rn '[area] p' $file

正则Regular Expression
推荐使用扩展语法sed -r ...,统一的规范。
扩展 默认 效果
\?
* *
+ \+
{n1} \{n1\}
{n1,n2} \{n1,n2\}
{n1,} \{n1,\}
^ ^
$ $
[] []
[^] [^]
[a-zA-Z0-9] [a-zA-Z0-9]
\w \w 字母数字下划线
\W \W 字母数字下划线
\s \s
\S \S
() \(\)

    推荐阅读