sed行编辑器使用介绍

来源:互联网 发布:东村明子 知乎 编辑:程序博客网 时间:2024/05/01 00:43

语法:

sed  [options] '{command}[flags]'   [filename]   注意一般语法中出现的中括号为选填,大括号为必填

追加、插入  a  i
删除        d
修改        s(替换)c(更改)y(转换)
   p(打印)


eg:

echo "this is a test" |sed 'a\abc'

结果:

this is a test

abc

(sed 'a\abc'  \ 转义可以省略)


eg:

建立一个file文件,内容如下:

this is a beautiful dog.

this is a beautiful dog.

this is a beautiful dog.

this is a beautiful dog.

this is a beautiful dog.


sed 'a\"hello"' file  在file文件每行后添加hello(自动换行)

sed '1a\"hello"' file  在file文件第一行后添加hello(自动换行)

当然这些命令只是在内存中操作,并不会真是改变文件内容,具体怎样命令改变文件内容,在下面会具体说明。

sed 'd' file 全删光了
sed '2,5d' file 只剩下第3行

echo "this is a test"|sed 's/test/dog/'     命令行显示-------  this is a dog

sed 's/$/cat and dog/' file   在每行最后插入cat and dog; 其中$表示一行的最后

sed '5s/$/cat and dog/' file   在第五行最后插入

sed 's/^/#/' file    在每行前面添加#

sed '4s/^/#/' file  匹配第几行,在该行前面添加#

sed ‘2c\today is fine’ file 把第2行都改掉

sed ‘2c\today is fine\nhow are you’ file 把第2行都改掉,并添加一行

sed ‘2,4c\today is fine’ file 把第2行到第四行都改为today is fine

sed 'p' file  查看(此处会出现俩遍file文件内容,因为一遍是机器储存内容,一遍是内存内容)

---------------------sed命令选项

option
-e 多块部分修改
-f 调用文件里的命令
-n 内存 -i
-r  正则表达式

sed -e 's/is/as/;s/dog/cat/' file    -e不加也行

sed  -f  abc(文件)  file   abc为储存的命令行

sed   -i.bak  's/cat/dog/' file  生成bak文件,改错可以还原(把源文件备份为bak)

----------------------sed命令标致
flags
数字N   
p
g          sed    ‘s/dog/cat/g’file 全改
w写入      sed ‘s/dog/cat/gw file_new’file  把file文件里的所有dog全部改为cat,并保存为file_new文件

---------------------------
统计多少行
sed  -n '$=' file




0 0