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

后端 未结 11 1053
后悔当初
后悔当初 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:13
    grep -m6 "string" cov.txt
    

    This searches only the first 6 lines for string

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

    grep -A 10 <Pattern>

    This is to grab the pattern and the next 10 lines after the pattern. This would work well only for a known pattern, if you don't have a known pattern use the "head" suggestions.

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

    For folks who find this on Google, I needed to search the first n lines of multiple files, but to only print the matching filenames. I used

     gawk 'FNR>10 {nextfile} /pattern/ { print FILENAME ; nextfile }' filenames
    

    The FNR..nextfile stops processing a file once 10 lines have been seen. The //..{} prints the filename and moves on whenever the first match in a given file shows up. To quote the filenames for the benefit of other programs, use

     gawk 'FNR>10 {nextfile} /pattern/ { print "\"" FILENAME "\"" ; nextfile }' filenames
    
    0 讨论(0)
  • 2021-01-30 08:19
    head -10 log.txt | grep -A 2 -B 2 pattern_to_search
    

    -A 2: print two lines before the pattern.

    -B 2: print two lines after the pattern.

    head -10 log.txt # read the first 10 lines of the file.
    
    0 讨论(0)
  • 2021-01-30 08:20

    An extension to Joachim Isaksson's answer: Quite often I need something from the middle of a long file, e.g. lines 5001 to 5020, in which case you can combine head with tail:

    head -5020 file.txt | tail -20 | grep x
    

    This gets the first 5020 lines, then shows only the last 20 of those, then pipes everything to grep.

    (Edited: fencepost error in my example numbers, added pipe to grep)

    0 讨论(0)
  • 2021-01-30 08:28
    grep "pattern" <(head -n 10 filename)
    
    0 讨论(0)
提交回复
热议问题