Linux系统:sed 字符替换命令,linuxsed


sed 命令

sed 是一种几乎包括在所有 UNIX 平台(包括 Linux)的轻量级流编辑器。sed 主要是用来将数据进行选取、替换、删除、新增的命令。

格式:

sed [选项] ‘[动作]’ 文件名

选项:

-n:一般 sed 命令会把所有数据都输出到屏幕,如果加入此选项则只会把经过 sed 命令处理的行输出到屏幕。 -e:允许对输入的数据应用多条 sed 命令编辑。 -i:用 sed 的修改结果直接修改读取数据的文件,而不是由屏幕输出。

动作:

a:追加,在当前行后添加一行或多行。 c:行替换,用 c 后面的字符串替换原数据行。 i:插入,在当前行前插入一行或多行。 d:删除,删除指定的行。 p:打印,输出指定的行。 s:字符替换,用一个字符串替换另外一个字符串。格式为“行范围s/旧字串/新字串/g”(和 vim 中的替换格式类似)

行数据操作

[root@localhost ~]# sed '2p' student.txt #没有 -n 选项输出所有内容,而且会重复,'2p' 代表打印第二行
ID  Name    Gender  Mark
1   stu1    F       95
1   stu1    F       95
2   stu2    F       85
3   stu3    F       75
[root@localhost ~]# sed -n '2p' student.txt #有-n 选项则打印指定行
1   stu1    F   95
[root@localhost ~]# sed '2d' student.txt #'2d' 代表删除第二行内容,不修改原文件
ID  Name    Gender  Mark
2   stu2    F       85
3   stu3    F       75
[root@localhost ~]# sed '2,4d' student.txt #'2,4d' 代表删除第二行到第四行所有内容,不修改原文件
ID  Name    Gender  Mark
[root@localhost ~]# sed '2a hello' student.txt #在第二行后追加一行内容为 hello,不修改原文件
ID  Name    Gender  Mark
1   stu1    F       95
hello
2   stu2    F       85
3   stu3    F       75

[root@localhost ~]# sed '2i hello' student.txt #在第二行前插入一行内容为 hello,不修改原文件
ID  Name    Gender  Mark
hello
1   stu1    F       95
2   stu2    F       85
3   stu3    F       75
[root@localhost ~]# sed '4c test' student.txt #替换第四行内容为 test,不修改原文件
ID  Name    Gender  Mark
1   stu1    F       95
2   stu2    F       85
test

字符串替换

sed ‘s/旧字串/新字串/g’ 文件名 # g 代表替换所有字符串

[root@localhost ~]# sed '4s/75/100/g' student.txt #替换第四行的 75 为 100,不修改原文件
ID  Name    Gender  Mark
1   stu1    F       95
2   stu2    F       85
3   stu3    F       100

[root@localhost ~]# sed -i '4s/75/100/' student.txt # -i 选项会修改原文件内容,但不再打印到屏幕
[root@localhost ~]# cat student.txt #原文件内容已更改 
ID  Name    Gender  Mark
1   stu1    F       95
2   stu2    F       85
3   stu3    F       100
[root@localhost ~]# sed -e 's/stu1//g;s/stu3//g' student.txt #-e 执行多条语句,用分号隔开,将 stu1 和 stu3 内容替换为空,替换原文件用 -ie,-ei 会报错
ID  Name    Gender  Mark
1           F       95
2   stu2    F       85
3           F       100

相关内容