linux中sed的用法详解(对行数据的添加、删除等)


sed使用语法
[root@fwq test]# sed --help
用法: sed [选项]... {脚本(如果没有其他脚本)} [输入文件]...

-n, --quiet, --silent 取消自动打印模式空间
-e 脚本, --expression=脚本 添加“脚本”到程序的运行列表
-f 脚本文件, --file=脚本文件 添加“脚本文件”到程序的运行列表
--follow-symlinks follow symlinks when processing in place; hard links will still be broken.
-i[SUFFIX], --in-place[=SUFFIX]
edit files in place (makes backup if extension supplied).
The default operation mode is to break symbolic and hard links.
This can be changed with --follow-symlinks and --copy.
-c, --copy
use copy instead of rename when shuffling files in -i mode.
While this will avoid breaking links (symbolic or hard), the
resulting editing operation is not atomic. This is rarely
the desired mode; --follow-symlinks is usually enough, and
it is both faster and more secure.
-l N, --line-length=N 指定“l”命令的换行期望长度
--posix 关闭所有 GNU 扩展
-r, --regexp-extended 在脚本中使用扩展正则表达式
-s, --separate 将输入文件视为各个独立的文件而不是一个长的连续输入
-u, --unbuffered 从输入文件读取最少的数据,更频繁的刷新输出
--help 打印帮助并退出
--version 输出版本信息并退出

打印出行号,并删除2-5行

[root@fwq test]# nl /etc/passwd | sed '2,5d' |more
1 root:x:0:0:root,704,03738888766,03738888766:/root:/bin/bash
6 sync:x:5:0:sync:/sbin:/bin/sync
7 shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
8 halt:x:7:0:halt:/sbin:/sbin/halt
9 mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
10 uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin

打印出行号,只删除2-5行

[root@fwq test]# nl /etc/passwd | sed '2d' |more
1 root:x:0:0:root,704,03738888766,03738888766:/root:/bin/bash
3 daemon:x:2:2:daemon:/sbin:/sbin/nologin
4 adm:x:3:4:adm:/var/adm:/sbin/nologin
5 lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

打印出行号,删除第2行以后所有内容

[root@fwq test]# nl /etc/passwd | sed '2,$d'
1 root:x:0:0:root,704,03738888766,03738888766:/root:/bin/bash
[root@fwq test]#

打印出行号,在第2行后加上“drink tea”

[root@fwq test]# nl /etc/passwd |sed '2a drink tea' | more
1 root:x:0:0:root,704,03738888766,03738888766:/root:/bin/bash
2 bin:x:1:1:bin:/bin:/sbin/nologin
drink tea
3 daemon:x:2:2:daemon:/sbin:/sbin/nologin
4 adm:x:3:4:adm:/var/adm:/sbin/nologin

打印出行号,加入2行“drink tea or drink beer”

[root@fwq test]# nl /etc/passwd |sed '2a drink tea or ...\
drink beer?' | more
1 root:x:0:0:root,704,03738888766,03738888766:/root:/bin/bash
2 bin:x:1:1:bin:/bin:/sbin/nologin
drink tea or ...
drink beer?
3 daemon:x:2:2:daemon:/sbin:/sbin/nologin
4 adm:x:3:4:adm:/var/adm:/sbin/nologin

打印出行号,将第2-5行的内容更换成“No 2-5”

[root@fwq test]# nl /etc/passwd | sed '2,5c No 2-5 number' | more
1 root:x:0:0:root,704,03738888766,03738888766:/root:/bin/bash
No 2-5 number
6 sync:x:5:0:sync:/sbin:/bin/sync
7 shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
8 halt:x:7:0:halt:/sbin:/sbin/halt

打印出行号,仅列出第5-7行的内容

[root@fwq test]# nl /etc/passwd | sed -n '5,7p'
5 lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
6 sync:x:5:0:sync:/sbin:/bin/sync
7 shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown

相关内容