Use grep to report back only line numbers

前端 未结 8 1448
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 13:40

I have a file that possibly contains bad formatting (in this case, the occurrence of the pattern \\\\backslash). I would like to use grep to return

相关标签:
8条回答
  • 2020-12-04 14:18

    All of these answers require grep to generate the entire matching lines, then pipe it to another program. If your lines are very long, it might be more efficient to use just sed to output the line numbers:

    sed -n '/pattern/=' filename
    
    0 讨论(0)
  • 2020-12-04 14:20

    try:

    grep -n "text to find" file.ext | cut -f1 -d:
    
    0 讨论(0)
  • 2020-12-04 14:30

    To count the number of lines matched the pattern:

    grep -n "Pattern" in_file.ext | wc -l 
    

    To extract matched pattern

    sed -n '/pattern/p' file.est
    

    To display line numbers on which pattern was matched

    grep -n "pattern" file.ext | cut -f1 -d:
    
    0 讨论(0)
  • 2020-12-04 14:31

    I recommend the answers with sed and awk for just getting the line number, rather than using grep to get the entire matching line and then removing that from the output with cut or another tool. For completeness, you can also use Perl:

    perl -nE '/pattern/ && say $.' filename
    

    or Ruby:

    ruby -ne 'puts $. if /pattern/' filename
    
    0 讨论(0)
  • 2020-12-04 14:35

    If you're open to using AWK:

    awk '/textstring/ {print FNR}' textfile
    

    In this case, FNR is the line number. AWK is a great tool when you're looking at grep|cut, or any time you're looking to take grep output and manipulate it.

    0 讨论(0)
  • 2020-12-04 14:36

    using only grep:

    grep -n "text to find" file.ext | grep -Po '^[^:]+'

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