如何使用 shell 命令打印与模式匹配的相应行的行号?

如何使用 shell 命令打印与模式匹配的相应行的行号?

文件,

.false alarm is bla no. 11
.no alarm generated is bla
.application will be killed is bla wall command
.doc file is document file with .doc extension
.no authority for this selection bla

现在我想要在输出文件中打印仅包含单词的行bla(或者也可能是数字)

输出将是这样的,

1 .false alarm is bla no. 11
2 .no alarm generated is bla
3 .application will be killed is bla wall command
5 .no authority for this selection bla

答案1

许多工具都很方便:

  • -nofgrep正是您正在寻找的。

    grep -n 'bla' file
    
  • 或者awk

    awk '/bla/{print NR":"$0}' file
    
  • 或者perl

    perl -ne 'print $.,":",$_ if /bla/' file
    
  • 或者sed

    sed '/bla/!d;=' file |sed 'N;s/\n/:/'
    

相关内容