从命令行使用正则表达式提取数字

Shr*_*ray 0 grep text-processing regular-expression

我正在使用一个工具来计算 javascript 文件的 cylomatic 复杂性。

例子:

jsc --minimal test.js
Run Code Online (Sandbox Code Playgroud)

此命令将提供以下输出。

????????????????????????????????????????????????????????????????
? 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
Run Code Online (Sandbox Code Playgroud)

现在我用

jsc --minimal test.js | grep "Cyclomatic:"
Run Code Online (Sandbox Code Playgroud)

这给了我输出

Cyclomatic: min 4 mean 4.0 max 4
Run Code Online (Sandbox Code Playgroud)

现在我有一个正则表达式,Cyclomatic:[\s]*min[\s]+([0-9]+)但我无法使用它来提取显示最小 Cylomatic 值的数字。

有什么帮助我如何在终端输出上输出 Min 或 Max Cyclomatic 复杂度值的值?

pLu*_*umo 5

如果您知道此行始终具有相同的格式,则可以使用简单的cut

cut -d' ' -f3
Run Code Online (Sandbox Code Playgroud)

或者awk你可以做整件事,包括你的第一件事grep

awk '$1 == "Cyclomatic:" {print $3}'
Run Code Online (Sandbox Code Playgroud)

如果该行可能会更改,请使用sed

sed -E 's/.*( min )([0-9]+).*/\2/'
Run Code Online (Sandbox Code Playgroud)

或者grep -P如果可用:

grep -Po ' min \K[0-9]+'
Run Code Online (Sandbox Code Playgroud)

或正常grep

grep -o 'min [0-9]\+'
Run Code Online (Sandbox Code Playgroud)

这将返回min 4,您可以轻松过滤添加另一个grepcut

grep -o '[0-9]\+$'
# or
cut -d' ' -f2
Run Code Online (Sandbox Code Playgroud)