你如何grep文件并获得接下来的5行

时间:2013-10-09 13:55:54

标签: shell grep

我如何grep 19:55的文件并获取1,2,3,4,5行?

2013/10/08 19:55:27.471
Line 1
Line 2
Line 3
Line 4
Line 5

2013/10/08 19:55:29.566
Line 1
Line 2
Line 3
Line 4
Line 5

3 个答案:

答案 0 :(得分:167)

你想:

grep -A 5 '19:55' file

来自man grep

Context Line Control

-A NUM, --after-context=NUM

Print NUM lines of trailing context after matching lines.  
Places a line containing a gup separator (described under --group-separator) 
between contiguous groups of matches.  With the -o or --only-matching
option, this has no effect and a warning is given.

-B NUM, --before-context=NUM

Print NUM lines of leading context before matching lines.  
Places a line containing a group separator (described under --group-separator) 
between contiguous groups of matches.  With the -o or --only-matching
option, this has no effect and a warning is given.

-C NUM, -NUM, --context=NUM

Print NUM lines of output context.  Places a line containing a group separator
(described under --group-separator) between contiguous groups of matches.  
With the -o or --only-matching option,  this  has  no effect and a warning
is given.

--group-separator=SEP

Use SEP as a group separator. By default SEP is double hyphen (--).

--no-group-separator

Use empty string as a group separator.

答案 1 :(得分:3)

一些awk版本。

awk '/19:55/{c=5} c-->0'
awk '/19:55/{c=5} c && c--'

找到模式后,设置c=5
如果c为真,则打印并减少c

的数量

答案 2 :(得分:2)

这是一个sed解决方案:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;

public class DateTest{
    public static void main(String[] args) throws ParseException{
        System.out.println("Current time in milliseconds: " + System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss MM/dd/yyyy");

        String dateAndTime1 = "2:30:00 1/23/2017";
        String dateAndTime2 = "1:45:00 5/23/2015";

        Date date1 = format.parse(dateAndTime1);
        Date date2 = format.parse(dateAndTime2);
        long difference = date1.getTime() - date2.getTime();


        System.out.println("The difference in milliseconds is " + difference);
    }
}