使用sed或awk显示指定行内容

文件内容为

[root@test1 test]# cat file.test
1
2
3
4
5
6
7
8
9
10

1. 显示第二行内容(指定行)

  • sed
[root@test1 test]# sed -n '2p' file.test
2
  • awk
[root@test1 test]# awk 'NR==2 {print $0}' file.test
2
[root@test1 test]# awk '{if(NR==2)print $0}' file.test
2

2. 显示第三行至第五行内容(指定行范围)

  • sed
[root@test1 test]# sed -n '3,5p' file.test
3
4
5
  • awk
[root@test1 test]# awk '{if(NR>2&&NR<6) print $0}' file.test
3
4
5
  • grep
[root@test1 test]# grep -C 1 4 file.test
3
4
5

3. 显示奇数行与偶数行

  • sed
[root@test1 test]# sed -n '1~2p' file.test
1
3
5
7
9
[root@test1 test]# sed -n '2~2p' file.test
2
4
6
8
10
[root@test1 test]# sed -n 'p;n' file.test
1
3
5
7
9
[root@test1 test]# sed -n 'n;p' file.test
2
4
6
8
10
  • awk
[root@test1 test]# awk 'NR%2==1' file.test
1
3
5
7
9
[root@test1 test]# awk 'NR%2==0' file.test
2
4
6
8
10
[root@test1 test]# awk '{if(NR%2==1) print $0}' file.test
1
3
5
7
9
[root@test1 test]#
[root@test1 test]# awk '{if(NR%2==0) print $0}' file.test
2
4
6
8
10

4. 显示匹配到的行

  • sed
[root@test1 test]# sed -n '/5/p' file.test
5 line 5
  • awk
[root@test1 test]# awk '/5/' file.test
5 line 5
  • grep
[root@test1 test]# grep 5 file.test
5 line 5
发布于:2019-11-14 11:17:03