Issue
In PHP I am searching and counting all the use cases of some classes in almost all files, with grep
.
\exec("grep -orE '" . $classesBarred . "' ../../front/src/components | sort | uniq -c", $allClassesCount);
Where $classesBarred
contains a string of classes like search-unfocused|bg-app|enlarged-window
(but much more).
The current result is
' 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',
.... (plus a few hundred more lines like these)
I would need the result in an array, something like:
[
{show: 38}, {action: 123}, {search-unfocused: 90}, {....}
]
EDIT:
@Freeman provided a solution to my question here, using awk
grep -orE "btn-gray|btn-outline-white" ../../front/src/components | awk -F: '{print $2}' | awk -F/ '{print $NF}' | sort | uniq -c | awk '{print $2 "::" $1}'
which gave this result:
btn-gray::1
btn-outline-white::13
Solution
yes as I can see, your code uses awk
to rearrange output from grep
into two columns, one is class name, and two contains the count,
the the output is like this :
search-unfocused 90
bg-app 5
enlarged-window 12
now you can easily, parse this output into an array by PHP like this :
$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;
}
}
and the array result is like below :
[
"search-unfocused" => 90,
"bg-app" => 5,
"enlarged-window" => 12,
...
]
Update :
If you insist on using awk and sed, you can do it like this:
grep -orE "$classesBarred" ../../front/src/components | awk -F '/' '{print $NF}' | awk -F ':' '{print $2}' | sort | uniq -c | awk '{gsub(/^[ \t]+|[ \t]+$/, "", $2); print "{\""$2"\": "$1"},"}' | paste -sd '' | sed 's/,$//' | awk '{print "["$0"]"}'
and the result is like this :
[
{"show": 38},
{"action": 123},
{"search-unfocused": 90},
{....}
]
good luck!
Answered By - Freeman Answer Checked By - Willingham (WPSolving Volunteer)