26
10
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?
I thought it was a neat command so I tried it on an existing 5k file that I found on my ubuntu vm. If I am not mistaken, the order of the commands is wrong. It should be
grep -o -n '[{}]' file | cut -d : -f 1 | uniq -c
.-w1
isn't needed either. The difference is 12 lines vs 118! – Dude named Ben – 2014-06-20T19:25:39.877@Vic, thanks for noticing it! The
-w1
option ofuniq
was blocking the comparison to the first character, therefore only working on line numbers of 1 digit. Changing the order, as you suggested, makes it unnecessary. – Moebius – 2014-06-22T07:48:34.430Thanks - google found lots of regex hits on SU, but not that one on SO, which doesn't even seem to have a regex tag. The
sort
isn't strictly necessary as grep's output is sorted by line number, but I guess it's good practice beforeuniq
. – Chris H – 2014-06-16T10:45:03.0402Probably not tagged
regex
because the regex is the easy part. – Tom Zych – 2014-06-16T10:51:51.710Is it actually necessary to
sort -n
? Doesn't it come out in line number order anyway? – Tom Zych – 2014-06-16T10:52:31.167You are right,
sort -n
is not necessary. Thanks. – Moebius – 2014-06-16T10:58:23.360@TomZych, it turned out you were right, but had I known that I might not have asked. The mental jump from grep to tag:regex was perhaps a bit too much though. – Chris H – 2014-06-16T12:54:59.077