Query for replacing sort, uniq and cut linux commands

I used to analyze logs (such as nginx logs) using some linux commands.
For example, if I want to extract the list of IPs that visited my website I use this command (we suppose that IPs are in the first column)

cat /var/log/nginx/access.log | cut -d ‘"’ -f1 | sort | uniq -c | sort -n

So the output would be a list of IPs and, for each IP, also the number of HTTP requests that it made, sorted in ascending or descending order.

A possible output would be:


that means that in my log I have five occurences in which there is the first IP and ten occurrences in which there is the second one.

Now I would like to do the same thing using Grafana.
I configured Loki to ingest logs and I would create a dashboard in which there is a panel displaying this information.

I tried a lot of queries, but I didn’t manage to find the correct one.

For instance, this is a query that I tried in Grafana explore tab

sum by(ip) (count_over_time({path=“/var/log/nginx/access.log”} | regexp clientip="(?P<ip>\S+)" [$__interval])) but it only extracts IPs, it doesn’t give me the output of sort | uniq -c | sort -n command.

I also tried to use transformation, but the result it’s not what I am expecting: I had a table with URLs and occurences, but I have to choose the URL from a dropdown menu.
To be clear, this is what I got until now

And this is what I get from my Linux command

So how can I “translate” this linux command cat /var/log/nginx/access.log | cut -d ‘"’ -f1 | sort | uniq -c | sort -n into a Grafana/Loki query?

How can I create a query (and a panel) that gives me the same output of my Linux commands?

I found this video Grafana Loki sneak peek: Generate Ad-hoc metrics from your NGINX Logs - YouTube

It seems to have panels that I need (at 1:27 you can see Top User Agents, Top IPs, Top HTTP Referers, Top Requested HTML Pages), but it’s not shown the query used to create those panels.

Do you have any ideas?

Thanks in advance

Check out the topk function here: Metric queries | Grafana Loki documentation

Using your example, something like this may be what you are looking for:

topk(10, sum by (ip) (
    {path=“/var/log/nginx/access.log”} | regexp clientip="(?P<ip>\S+)"