Group search results into groups and store as an array of objects
P粉198814372
P粉198814372 2023-09-10 23:18:31
0
1
533

In PHP I use grep to search and count all cases of certain classes in almost all files.

\exec("grep -orE '" . $classesBarred . "' ../../front/src/components | sort | uniq -c", $allClassesCount);

where $classesBarred contains class strings similar to search-unfocused|bg-app|enlarged-window (but 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',
....(还有几百行类似的结果)

I need to save the results in an array, similar to:

[
  {show: 38}, {action: 123}, {search-unfocused: 90}, {....}
]

edit: @Freeman provided a solution 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}'

The following results were obtained:

btn-gray::1
btn-outline-white::13

P粉198814372
P粉198814372

reply all(1)
P粉277824378

Yes, I can see that your code uses awk to rearrange the output of grep into two columns, one column is the class name and the other is the count, The output results are as follows:

search-unfocused 90
bg-app 5
enlarged-window 12

Now you can parse this output into an array through PHP, the code is as follows:

$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;
  }
}

The results of the array are as follows:

[
  "search-unfocused" => 90,
  "bg-app" => 5,
  "enlarged-window" => 12,
  ...
]

renew:
If you insist on using awk and sed, you can do this:

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},
  {....}
]
"]"}'

The results are as follows:

rrreee

Good luck!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template