by 29athrowaway · 5y ago · 0 comments
/usr/bin/awk '{print $7}' /home/logs/access_log.old | /usr/bin/sort | /usr/bin/uniq -c | /usr/bin/sort -r
1) If your PATH is well configured, you can omit the path to the binaries (i.e.: "/usr/bin/sort" becomes just "sort")2) Instead of using awk, you can just use cut.
# Delimit this line by the space character
# and get the 7th field
cut -d " " -f 7 /home/logs/access_log.old
3) Then, there's this: # This is not correct (lexicographic sort)
sort | uniq -c | sort -r
# This is correct (sort numerically)
sort | uniq -c | sort -rn
Why? because otherwise you get 1, 10, 2, 3, 4, 5, 7, 8, 9 instead of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.Try it yourself:
seq 1 10 | sort # lexicographic sort
seq 1 10 | sort -n # numeric sort
4) If you are just interested in the top 10, you can add sort | uniq -c | sort -rn | head -n 10Cut is much more painful to use.
It should just be `sort -rn | uniq`, no point in sorting the list twice.
"uniq -c" adds a column with the count of unique elements.
For the purposes of returning the most frequent elements, you can only do the final sort once that column has been added.