4

For the following text I need to count the lines that the number between parenthesis is in the range [10-20].

    This function's cyclomatic complexity is too high. (1)
    This function's cyclomatic complexity is too high. (2)
    This function's cyclomatic complexity is too high. (3)
    This function's cyclomatic complexity is too high. (4)
    This function's cyclomatic complexity is too high. (5)
    This function's cyclomatic complexity is too high. (6)
    This function's cyclomatic complexity is too high. (7)
    This function's cyclomatic complexity is too high. (8)
    This function's cyclomatic complexity is too high. (9)
    This function's cyclomatic complexity is too high. (10)
    This function's cyclomatic complexity is too high. (12)
    This function's cyclomatic complexity is too high. (13)
    This function's cyclomatic complexity is too high. (14)
    This function's cyclomatic complexity is too high. (15)
    This function's cyclomatic complexity is too high. (16)
    This function's cyclomatic complexity is too high. (17)

Im trying the following commands:

cat log.txt | grep -c "This function's cyclomatic complexity is too high. ([10-20])"
cat log.txt | grep -c "This function's cyclomatic complexity is too high. ([10,11,12,13,14,15,16,17,18,20])"

But didnt work. Whats the correct way to do it?

Rashomon
  • 5,962
  • 4
  • 29
  • 67

4 Answers4

3
grep -c "(1[0-9])\|(20)" filename
tso
  • 4,732
  • 2
  • 22
  • 32
1

grep is the wrong tool. You don't want to be using a regex to do numerical comparison. Try:

awk "/This function's cyclomatic complexity is too high./"'$2 >= 10 && $2 <=20 {c++} END {print c}' FS='[()]' pruebascript.txt

Note that you probably can simplify to:

awk '$2 >= 10 && $2 <=20 {c++} END {print c}' FS='[()]' pruebascript.txt

depending on your actual data.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
1

I do not have access to a terminal so this is untested, but try cat pruebascript.txt | grep -c "This function's cyclomatic complexity is too high. (1[0-9]|20)". Your regular expression in grep asks for 1 or 2, and 2 or 0.

1[0-9] will match anything between 10 to 19 as well as 20.

Read more about numeric ranges regex: https://www.regular-expressions.info/numericranges.html

JCJ
  • 303
  • 3
  • 13
1

To list distinct strings for grep you surround them with \(\) and separate with \|, like this:

$ grep "This function's cyclomatic complexity is too high. (\(10\|11\|12\))" file
This function's cyclomatic complexity is too high. (10)
This function's cyclomatic complexity is too high. (12)
James Brown
  • 36,089
  • 7
  • 43
  • 59