在PHP中,我使用grep
在几乎所有文件中搜索和计算某些类的所有用例。
\exec("grep -orE '" . $classesBarred . "' ../../front/src/components | sort | uniq -c", $allClassesCount);
其中$classesBarred
包含类似于search-unfocused|bg-app|enlarged-window
(但更多)的类字符串。
当前结果为
' 2 ../../front/src/components/Actions/ActionOwner.vue:show', ' 1 ../../front/src/components/Actions/ActionOwner.vue:action', ' 1 ../../front/src/components/Actions/ActionOwner.vue:show', ' 5 ../../front/src/components/Actions/ActionOwner.vue:action', ' 1 ../../front/src/components/Actions/ActionOwner.vue:show', ....(还有几百行类似的结果)
我需要将结果保存在一个数组中,类似于:
[ {show: 38}, {action: 123}, {search-unfocused: 90}, {....} ]
编辑:
@Freeman在这里提供了一个解决方案,使用awk
grep -orE "btn-gray|btn-outline-white" ../../front/src/components | awk -F: '{打印 $2}' | awk -F/ '{print $NF}' |排序| uniq-c| awk '{print $2 "::" $1}'
得到了以下结果:
btn-gray::1 btn-outline-white::13
P粉2778243782023-09-11 20:46:24
是的,我可以看到,你的代码使用 awk
将 grep
的输出重新排列为两列,一列是类名,另一列是计数,
输出结果如下:
search-unfocused 90 bg-app 5 enlarged-window 12
现在你可以通过 PHP 将这个输出解析为一个数组,代码如下:
$results = array(); foreach ($allClassesCount as $line) { $parts = explode(" ", $line); $className = $parts[0]; $count = (int)$parts[1]; if (!isset($results[$className])) { $results[$className] = $count; } else { $results[$className] += $count; } }
数组的结果如下:
[ "search-unfocused" => 90, "bg-app" => 5, "enlarged-window" => 12, ... ]
更新:
如果你坚持使用 awk 和 sed,你可以这样做:
grep -orE "$classesBarred" ../../front/src/components | awk -F '/' '{print $NF}' | awk -F ':' '{print }' | sort | uniq -c | awk '{gsub(/^[ \t]+|[ \t]+$/, "", ); print "{\"""\": ""},"}' | paste -sd '' | sed 's/,$//' | awk '{print "["[ {"show": 38}, {"action": 123}, {"search-unfocused": 90}, {....} ]"]"}'
结果如下:
rrreee祝你好运!