Reputation: 31
This is the grep command I have:
grep 'Query failed' file.txt | grep -o '\bT\w*'
Search for string 'Query failed' and then it gives me the words starting with T.
Result is for example:
Test1
Test1
Test2
Test2
Test2
Test3
Test4
Test4
Is it possible to get a result like:
Test1 = 2
Test2 = 3
Test3 = 1
Test4 = 2
Thanks a lot in advance
Upvotes: 3
Views: 61
Reputation: 74665
One option, extending your current pipeline, would be to use uniq
to count the occurrences and awk
to reformat the line:
your_commands | uniq -c | awk '{ print $2 " = " $1 }'
Note that uniq
expects to receive sorted input, so you may need to pipe to sort
beforehand.
Alternatively, you could do the whole thing in awk:
awk '/Query failed/ { for (i = 1; i <= NF; ++i) if ($i ~ /^T/) ++seen[$i] }
END { for (i in seen) print i " = " seen[i] }' file
On lines matching the pattern, loop through all the words and keep a count of any starting with "T". Once the file has been processed, loop through the array and print the results.
Note that associative arrays are unsorted in awk, so the order of the output may vary.
Upvotes: 3
Reputation: 781370
Pipe it to sort
and uniq -c
to count all the repetitions.
grep 'Query failed' file.txt | grep -o '\bT\w*' | sort | uniq -c
Output will be:
2 Test1
3 Test2
1 Test3
2 Test4
From your example, it looks like the original file is already sorted. If so, you can omit the sort
step.
Upvotes: 3