I am using a tool to calculate cylomatic complexity of a javascript file.


jsc --minimal test.js

This command will give the following output.

│ File                │ LOC │ Cyclomatic │ Halstead difficulty │
│ /home/shray/test.js │ 23  │ 4          │ 10                  │
Cyclomatic: min 4 mean 4.0 max 4
Halstead: min 10 mean 10.0 max 10

Now I use

jsc --minimal test.js | grep "Cyclomatic:"

which gives me output as

Cyclomatic: min 4 mean 4.0 max 4

Now I have a regex, Cyclomatic:[\s]*min[\s]+([0-9]+) but I am not able to use it to extract the number showing minimum Cylomatic value.

Any help how can I just ouput the value of Min or Max Cyclomatic complexity value on the terminal output?

  • Cyclomatic: min 4 mean 4.0 max 4 this structure will always remain same? Just the values will change? – Pacifist Oct 4 '19 at 6:35
  • "I am not able to use it" how did you try and what happened? Do you have GNU grep (are you using Linux or UNIX)? – roaima Oct 4 '19 at 6:38
  • I don't know how to use this regex in terminal to extract the value. I tried using the regex with grep but it did not output anything then. I am using Ubuntu16 @roima – Shray Oct 4 '19 at 6:41
  • Yes the structure remains same @Pacifist – Shray Oct 4 '19 at 6:41
  • ...|awk '/Cyclomatic/ {print $3,$7}' can you try this then ? It will give you min and max numbers only for Cyclomatic. – Pacifist Oct 4 '19 at 6:43

If you know that this line is always of the same format, you can use a simple cut:

cut -d' ' -f3

or with awk you can do the whole thing including your first grep:

awk '$1 == "Cyclomatic:" {print $3}'

If the line might change, use sed:

sed -E 's/.*( min )([0-9]+).*/\2/'

or grep -P if available:

grep -Po ' min \K[0-9]+'

or normal grep:

grep -o 'min [0-9]\+'

This returns min 4, which you can easily filter adding another grep or cut

grep -o '[0-9]\+$'
# or
cut -d' ' -f2

In Linux, using a look-behind (-P is only in Gnu grep):

jsc --minimal test.js | grep -Po '(?<=Cyclomatic: min )\d+'

(this extracts the first group of digits that follows "Cyclomatic: min ").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.