1. 程式人生 > 其它 >linux系統中sed命令提取指定的行

linux系統中sed命令提取指定的行

1、測試資料如下:

[root@centos79 test]# seq 10 > a.txt
[root@centos79 test]# ls
a.txt
[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9
10

2、提取第2行

[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9
10
[root@centos79 test]# sed -n '2p' a.txt
2

3、提取第2行到第7行

[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9 10 [root@centos79 test]# sed -n '2,7p' a.txt 2 3 4 5 6 7

4、只提取第2行和第7行

[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9
10
[root@centos79 test]# sed -n '2p;7p' a.txt
2
7

5、提取奇數行

[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9
10
[root@centos79 test]# sed -n '1~2p' a.txt
1
3
5
7
9

6、提取偶數行

[root@centos79 test]# cat a.txt
1 2 3 4 5 6 7 8 9 10 [root@centos79 test]# sed -n '2~2p' a.txt 2 4 6 8 10

7、提取3倍數行

[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9
10
[root@centos79 test]# sed -n '3~3p' a.txt
3
6
9

利用正則表示式提取特定行。

8、測試資料如下:

[root@centos79 test]# seq 15 > a.txt
[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9
10 11 12 13 14 15

9、提取匹配2的行

[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@centos79 test]# sed -n '/2/p' a.txt
2
12

10、提取沒有匹配2的行

[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@centos79 test]# sed -n '/2/!p' a.txt
1
3
4
5
6
7
8
9
10
11
13
14
15

11、提取同時匹配2和5的行

[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@centos79 test]# sed -n '/2\|5/p' a.txt
2
5
12
15

12、提取沒有匹配2或者5的行

[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@centos79 test]# sed -n '/2\|5/!p' a.txt
1
3
4
6
7
8
9
10
11
13
14

13、提取以2開頭的行

[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@centos79 test]# sed -n '/^2/p' a.txt
2

13、提取以2結尾的行

[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@centos79 test]# sed -n '/2$/p' a.txt
2
12

14、同時提取以2開頭或者以5開頭的行

[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@centos79 test]# sed -n '/^2\|^5/p' a.txt
2
5

15、同時提取以2和5結尾的行

[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@centos79 test]# sed -n '/2$\|5$/p' a.txt
2
5
12
15

16、提取以1開頭以5結尾的行

[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9
13340
213435
1332425
13
1434
13245
[root@centos79 test]# sed -n '/^1.*5$/p' a.txt
1332425
13245

17、提取3的倍數行以外的行

[root@centos79 test]# cat a.txt
1
2
3
4
5
6
7
8
9
10
[root@centos79 test]# sed -n '3~3!p' a.txt
1
2
4
5
7
8
10