Can I grep only the first n lines of a file?

后端 未结 11 1014
后悔当初
后悔当初 2021-01-30 07:33

I have very long log files, is it possible to ask grep to only search the first 10 lines?

相关标签:
11条回答
  • 2021-01-30 08:32

    You can use the following line:

    head -n 10 /path/to/file | grep [...]
    
    0 讨论(0)
  • 2021-01-30 08:35

    The output of head -10 file can be piped to grep in order to accomplish this:

    head -10 file | grep …
    

    Using Perl:

    perl -ne 'last if $. > 10; print if /pattern/' file
    
    0 讨论(0)
  • 2021-01-30 08:38

    Or use awk for a single process without |:

    awk '/your_regexp/ && NR < 11' INPUTFILE
    

    On each line, if your_regexp matches, and the number of records (lines) is less than 11, it executes the default action (which is printing the input line).

    Or use sed:

    sed -n '/your_regexp/p;10q' INPUTFILE 
    

    Checks your regexp and prints the line (-n means don't print the input, which is otherwise the default), and quits right after the 10th line.

    0 讨论(0)
  • 2021-01-30 08:39

    The magic of pipes;

    head -10 log.txt | grep <whatever>
    
    0 讨论(0)
  • 2021-01-30 08:39

    You have a few options using programs along with grep. The simplest in my opinion is to use head:

    head -n10 filename | grep ...
    

    head will output the first 10 lines (using the -n option), and then you can pipe that output to grep.

    0 讨论(0)
提交回复
热议问题