sed & awk 101 hacks 学习笔记 -sed

sed 基本语法:
sed options ‘commands’ file
sed 首先从 file 中读取第一行,然后执行所有的 commands;
再读取第二行,执行 所有 sed-commands;
重复这个过程,直到 input-file 结束 。
(options是可选项,command必须加,如果直接sed file 会报missing commands,commands外面的’'可以不加)

commands可以为一个或多个

p : 打印command

一个是最简单形式,如:
sed -n p file:打印file所有内容到标准输出
多个稍微复杂,以两个为例,可以为command1&commmand2的与形式,也可以为command1 | command的或形式,如:
sed -n ‘/hi/p’ file :打印file中的匹配到hi的行
sed -n -e ‘/hi/p’ -e ‘/hello/p’ :打印file中匹配到hi或者hello的行
当commands很多时,可以用{}将所有commands包住,一行一个命令:
sed -n ‘{
/hi/p
/hello/p
/world/p
}’
当comands很多,而且有时需要后期修改时,上面更实用的方法是,将所有的commands写入文件file1中,用 -f调用文件:
此时 sed语法变为:
sed options -f file1 file

sed 内部执行过程查看另一篇博文:
https://blog.csdn.net/oTobias/article/details/99591929

(/hi/是匹配hi的行,/hi/不是command,执行sed -n ‘/hi/’ file也会报missing commands)

行地址范围:
两行之间用逗号隔开
sed -n ‘1,4p’ file:打印1到4行之间的所有行
sed -n -e ‘1p’ -e ‘4p’ file :只打印1行和4行
sed -n ‘/hi/,/hello/’ file 打印匹配到hi和hello之间的所有行
sed -n -e ‘/hi/p’ -e ‘/hello/p’ file :只打印匹配到hi和hello的行

n~m地址范围:从n行开始,每次加m行

sed -n 1~2p file 打印 1 3 5 7 9…行

$ :表示最后行
使用$表示最后行时注意加单引号’ ’ 不然sed会执行变量替换

sed -n 1,$p file:会自动寻找p变量,替换p的值,如果没有定义p的值,会报p:undefined variable,如果之前定义了p的值,如set p = 2,就会变成 sed -n 1,2 file,这也是错的,因为没有command,汇报missing commands。
所以分为两种情况:

最后行:sed -n ‘1,$p’ file :打印1到最后行内容

变量替换:sed -n "1,$p"p file :打印1到2行内容

(总结:单引号内$变量替换无效,而双引号内可以生效)
字符地址范围:
字符地址范围用在//内表示地址范围
^:字符开头
$:字符结尾

sed -n ‘/^$/p’ file :打印空行 (这个外面也需要加单引号,具体原因不清,总之特殊字符表范围时候根据情况在commands外加单引号或双引号)

d : 删除command

(需要注意的是它只删除模式空间的内容,和其他 sed 命令一样,命令 d 不会修改原始文件的内容。)
sed 2d file :模式空间第二行被删除,打印模式空间的其他行
如果不提供地址范围,sed 默认匹配所有行
sed d file 模式空间所有行被删除,打印为空

wnewfile:写command

sed wnewfile file:将file copy 为newfile(屏幕上默认会打印file内容)
sed -n wnewfile file :将file copy 为newfile(屏幕上不会打印file内容)

s:替换command

g:全局标志

1,2,3…数字标志(表示第1,2,3次出现的标志)

i:忽略大小写标志

e:执行命令标志(该标志可以将模式空间中的任何内容当做 shell 命令执行)

//:默认定界符
|| @@:可选定界符

&:替换内容引用匹配内容
sed ‘s/^.*/<&>/’ file :将每一行内容外面加<>
():引用分组(多个分组分别引用时,\1引用第一个分组)

正则表达式

^:行头
$:行尾
.:任意单个字符
…:任意两个字符
:匹配0次或多次
+:匹配1次或多次
\?:匹配0次或1次
[]:方括号字符集,匹配方括号任意一个字符
{m,n}:匹配m到n次
\b:字符边界 (\bxx xx\b \bxx\b)
\n:匹配引用
sed -n ‘/(the)\1/ p’ file \1引用the,所以匹配两个the
sed -n 's/(.
),(.),(.)/\2,\1, \3/p’ file :交换第1列和第2列内容

把 sed 当做命令解释器使用 :
要实现这个功能,需要在 sed 脚本最开始加入”#!/bin/sed –f”

$ vi myscript.sed
#!/bin/sed -f
#交换第一列和第二列
sed -n 's/(.),(.),(.)/\2,\1, \3/'p file
#把整行内容放入<>中
s/^.
/<&>/

#!/bin/sed -nf 可以屏蔽默认输出
初始文件如下:
在这里插入图片描述
sed脚本如下
在这里插入图片描述
执行完如下
在这里插入图片描述
-i:插入option
直接修改输入文件内容 (用重定向也可)

a:下一行插入内容command
sed '2 a hello ’ file :在第二行后插入hello
i:上一行插入内容command
c:修改内容
sed '2 c hello ’ file 第二行内容换成hello
y:字符转换
sed ‘y/a/b/’ file 将a换成b
sed ‘y/abcde/ABCDE/’ file 将所有的abcde换成对应的ABCDE,多个字符转换时,长度需保持一致

发布了43 篇原创文章 · 获赞 0 · 访问量 3046

猜你喜欢

转载自blog.csdn.net/oTobias/article/details/99621901