How to print the line numbers with corresponding line that matches a pattern using shell command?

46,781

Many tools can be handy:

  • -n of grep is exactly what you are looking for.

    grep -n 'bla' file
    
  • alternatively awk:

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

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

    sed '/bla/!d;=' file |sed 'N;s/\n/:/'
    
Share:
46,781

Related videos on Youtube

Nainita
Author by

Nainita

Updated on September 18, 2022

Comments

  • Nainita
    Nainita over 1 year

    File,

    .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
    

    Now what I want in my output file to print the lines which contains only the word bla (Or it may be number also)

    Output will be like this,

    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
    
    • Admin
      Admin almost 7 years
      awk 'i++ {if($1~/RRBS/) print i}' ../../bak/bak.db
  • Nainita
    Nainita over 8 years
    :-) yes... got the desired output. @jimmij
  • Admin
    Admin almost 2 years
    sed can also be sed -n '/bla/!d;=;p' file