Can grep show only words that match search pattern?

前端 未结 14 1806
忘掉有多难
忘掉有多难 2020-11-22 14:35

Is there a way to make grep output \"words\" from files that match the search expression?

If I want to find all the instances of, say, \"th\" in a number of files, I

14条回答
  •  独厮守ぢ
    2020-11-22 15:20

    I was unsatisfied with awk's hard to remember syntax but I liked the idea of using one utility to do this.

    It seems like ack (or ack-grep if you use Ubuntu) can do this easily:

    # ack-grep -ho "\bth.*?\b" *
    
    the
    the
    the
    this
    thoroughly
    

    If you omit the -h flag you get:

    # ack-grep -o "\bth.*?\b" *
    
    some-other-text-file
    1:the
    
    some-text-file
    1:the
    the
    
    yet-another-text-file
    1:this
    thoroughly
    

    As a bonus, you can use the --output flag to do this for more complex searches with just about the easiest syntax I've found:

    # echo "bug: 1, id: 5, time: 12/27/2010" > test-file
    # ack-grep -ho "bug: (\d*), id: (\d*), time: (.*)" --output '$1, $2, $3' test-file
    
    1, 5, 12/27/2010
    

提交回复
热议问题