1. 程式人生 > >Linux三劍客之sed基本應用

Linux三劍客之sed基本應用

sed命令基本應用

sed:三劍客之第二
實現對文件的增加 刪除 修改 查詢 過濾
命令格式:sed 選項 sed內置命令 文件
-i
-e
-n
a
i
d
p
s
g
創建文件tobedu.txt,輸入內容,並以此文件為例。
[root@toby ~]# cat -n tobyedu.txt
1 I am toby teacher!
2 I like badminton ball ,billiard ball and chinese chess!
3 our site is tobyedu.com
4
5 my qq num is 12345678.

  1. 打印2到4行
    [root@toby ~]# sed -n ‘2,4p‘ tobyedu.txt
    I like badminton ball ,billiard ball and chinese chess!
    our site is tobyedu.com

[root@toby ~]#
2.查詢不連續的行,只打印第1和第4行
[root@toby ~]# sed -n ‘1p;4p‘ tobyedu.txt
I am toby teacher!

[root@toby~]#
3.過濾出含有toby字符串的行.
[root@toby ~]# sed -n ‘/toby/p‘ tobyedu.txt
I am toby teacher!
our site is tobyedu.com
刪除含有toby字符串的行

[root@toby ~]# sed ‘/toby/d‘ tobyedu.txt
I like badminton ball ,billiard ball and chinese chess!

my qq num is 12345678.
4.將文件中的toby替換為tobygirl
[root@toby ~]# sed ‘s#toby#tobygirl#g‘ tobyedu.txt
I am tobygirl teacher!
I like badminton ball ,billiard ball and chinese chess!
our site is tobygirledu.com

my qq num is 12345678.

5.將文件中的toby字符串全部替換為tobygirl且把qq號12345678替換為87654321
[root@toby ~]# sed -e ‘s#toby#tobygirl#g‘ tobyedu.txt -e ‘s#12345678#87654321#g‘
I am tobygirl teacher!
I like badminton ball ,billiard ball and chinese chess!
our site is tobygirledu.com

my qq num is 87654321.
6.在tobyedu.txt文件第2行後追加文本i like linux。
[root@toby ~]# sed ‘2a i like linux‘ tobyedu.txt
I am toby teacher!
I like badminton ball ,billiard ball and chinese chess!
i like linux
our site is tobyedu.com

my qq num is 12345678.
7.在文件第2行插入文本i like tangwei
[root@toby ~]# sed ‘2i i like tangwei‘ tobyedu.txt
I am toby teacher!
i like tangwei
I like badminton ball ,billiard ball and chinese chess!
our site is tobyedu.com

my qq num is 12345678.
8.把第三行中的toby替換為xiaoting
[root@toby ~]# sed ‘3s#toby#xiaoting#g‘ tobyedu.txt
I am toby teacher!
I like badminton ball ,billiard ball and chinese chess!
our site is xiaotingedu.com

my qq num is 12345678.
9.把第一行到第三行的toby字符串替換為xiaoting
[root@toby ~]# sed ‘1,3s#toby#xiaoting#g‘ tobyedu.txt
I am xiaoting teacher!
I like badminton ball ,billiard ball and chinese chess!
our site is xiaotingedu.com

my qq num is 12345678.

Linux三劍客之sed基本應用