linux中输出匹配行的行号


1、测试数据

[root@centos7 test4]# ls
test.txt
[root@centos7 test4]# cat test.txt
e f j
d i x
a d g
c F w

2、grep 实现

[root@centos7 test4]# ls
test.txt
[root@centos7 test4]# cat test.txt
e f j
d i x
a d g
c F w
[root@centos7 test4]# grep -n "d" test.txt   ## 输出匹配d的行号
2:d i x
3:a d g

3、sed实现

[root@centos7 test4]# ls
test.txt
[root@centos7 test4]# cat test.txt
e f j
d i x
a d g
c F w
[root@centos7 test4]# sed -n '/d/=' test.txt  ##  输出匹配d的行号
2
3

4、awk实现

[root@centos7 test4]# ls
test.txt
[root@centos7 test4]# cat test.txt
e f j
d i x
a d g
c F w
[root@centos7 test4]# awk '$0 ~ /d/ {print NR}' test.txt  ## 输出匹配d的行号
2
3