linux - Grep: count number of matches per line

07
2014-07
  • Chris H

    I'm trying to get the number of matches (in this case occurrences of { or }) in each line of a .tex file.

    I know that the -o flag returns only the match, but it returns each match on a new line, even combined with the -n flag. I don't know of anything I could pipe this through to count the repeats. The -c flag only returns the total number of matches in the entire file - maybe I could pipe one line at a time to grep?

  • Answers
  • Moebius
    grep -o -n '[{}]' <filename> | cut -d : -f 1 | uniq -c
    

    The output will be something like:

    3 1
    1 2
    

    Meaning 3 occurrences in the first line and 1 in the second.

    Taken from http://stackoverflow.com/a/15366097/3378354 .

  • Scott

    Is using grep a requirement?  Here’s an alternative:

    sed 's/[^{}]//g' your_file | awk '{print NR, length }'
    

    The sed strips out all characters other than { and } (i.e., leaving only { and } characters), and then the awk counts the characters on each line (which are just the { and } characters).  To suppress lines with no matches,

    sed 's/[^{}]//g' your_file | awk '/./ {print NR, length }'
    

    Note that my solution assumes (requires) that the strings you are looking for are single characters.  Moebius’s answer is more easily adapted to multi-character strings.  Also, neither of our answers excludes quoted or escaped occurrences of the characters/strings of interest; e.g.,

    { "nullfunc() {}" }
    

    would be considered to contain four brace characters.


  • Related Question

    linux - grep - match anything but given filetype
  • Questioner

    I want to clean out my music library so I don't get any more "search for suitable plugin" messages from Rhythmbox when it sutubles across some WMA-Relic.

    I have the tools, but now I want to FIND these files. I can get a list of all music files with ls, then pipe this to grep and catch all the mp3s like this:

    ls */* | grep \.mp3$
    

    Now I want to filter OUT all the MP3s, how would I do that? I messed around a lot with ^ and ~ and ! but I never seemed to get anywhere. I KNOW for a fact there are a few WMAs in there, but why should I search manually when I have a computer xD

    Can anyone help?


  • Related Answers
  • Martin Hilton

    grep -v will return all lines that don't match your search query

    you can also use:

    find . ! -name "*.mp3"
    

    to do the whole thing in one command.

  • ayaz

    Have a look at the -v switch to grep, which inverts matching.