Extract Nth line after matching pattern

后端 未结 3 1411
借酒劲吻你
借酒劲吻你 2020-12-15 01:26

I want to extract the Nth line after a matching pattern using grep, awk or sed.

For example I have this piece of text:

3条回答
  •  旧巷少年郎
    2020-12-15 02:02

    Printing the lnbth line after first blank/empty line:

    Index of line to print (in bash shell):

    lnb=2
    
    • Using sed:

      sed -ne '/^\s*$/{:a;n;0~'"$lnb"'!ba;p;q}' my_file`
      
    • Using perl:

      perl -ne '/^\s+$/ && $k++;$k!=0 && $k++ && $k=='"$lnb"'+2 && (print,last)' my_file`
      

    Printing the lnbth line after regular-expression match:

    • Using sed:

      sed -ne '/regex/{:a;n;0~'"$lnb"'!ba;p;q}' my_file
      
    • Using perl:

      perl -ne '/regex/ && $k++;$k!=0 && $k++ && $k=='"$lnb"'+2 && (print,last)' my_file
      

      Bonus 1, Windows PowerShell (install Perl first) :

      $lnb=2
      
      perl -ne "/regex/ && `$k++;`$k!=0 && `$k++ && `$k==$lnb+2 && (print,last)" my_file
      

      Bonus 2, Windows DOS command line :

      set lnb=2
      
      perl -ne "/regex/ && $k++;$k!=0 && $k++ && $k==%lnb%+2 && (print,last)" my_file
      

    Printing ALL lnbth lines after regular-expression match:

    • Using perl(bash example):

      perl -ne '/regex/ && $k++;$k!=0 && $k++ && $k=='"$lnb"'+2 && (print,$k=0)' my_file
      

提交回复
热议问题