print all rows following matched row

廉价感情. 提交于 2020-01-06 08:50:11

问题


How can I print all rows after matching pattern in nth row, but ignore all before matched row including the matching row, here is an example :

row1 something in this row
row2 something in this row
row3 something in this row
row4 don't need to match the whole line, something like java String.contains()
row5 something in this row
row6 something in this row
row7 something in this row
row8 something in this row
row9 something in this row
row10 something in this row

I'm looking to print lines following the line which contains row4 anywhere in that row, is this possible with awk or sed, or any other way?

Output should be :

row5 something in this row
row6 something in this row
row7 something in this row
row8 something in this row
row9 something in this row
row10 something in this row

I've seen similar question :

Awk - print next record following matched record

But I'm not sure how to adapt it to fit my needs.


回答1:


If Perl is fine with you can do:

perl -ne 'print if($f); $f=1 if(/row4/)'

Code in Action




回答2:


Try this:

sed '1,/row4/d' inputfile



回答3:


You an use the following command:

grep -A 5 "row4" test.txt

The output will be:

row4
row5
row6
row7
row8
row9

-A goes for After and similary you can use -B key which goes for Before. 5 is the number of lines to output. You can choose whatever you want of course.




回答4:


This works, a guru could probably shorten it considerably:

#!/usr/bin/perl
$pat = shift(@ARGV);
$p = 0;
while(<>) {
  if ($p == 1) { print $_;}
  if ($_ =~ /$pat/) {
    $p = 1;
  }
}

From the cmdline:

$ ./p.pl dat4 datafile



回答5:


 awk 'c&&c>0;/row4/{c=5}' file



回答6:


awk -v pattern="row4" 'go {print} $0 ~ pattern {go = 1}' input_file


来源:https://stackoverflow.com/questions/4033385/print-all-rows-following-matched-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!