Skip to content

Instantly share code, notes, and snippets.

@adenosinew
Last active October 2, 2019 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adenosinew/5d8f9c70bf016f4c5dbca237fa5832e8 to your computer and use it in GitHub Desktop.
Save adenosinew/5d8f9c70bf016f4c5dbca237fa5832e8 to your computer and use it in GitHub Desktop.
[AWK intro] #linux #cmd
awk '{a+=$(NF-2)}END{print "Total:", a}' logs.txt
# Output:
# Total: 504
awk '{if ($(NF-2) == "200") {print $0}}' logs.txt
# Output:
# 07.46.199.184 [28/Sep/2010:04:08:20] "GET /robots.txt HTTP/1.1" 200 0 "msnbot"
awk '{print $1, $(NF-2) }' logs.txt
# Output:
# 07.46.199.184 200
# 123.125.71.19 304
awk '{print $1}' logs.txt
# Output:
# 07.46.199.184
# 123.125.71.19
# Another cool variable is NR, which is the row number being currently processed.
awk '{print NR ") " $1 " -> " $(NF-2)}' logs.txt
# Output:
# 1) 07.46.199.184 -> 200
# 2) 123.125.71.19 -> 304
awk '{print $2}' logs.txt | awk 'BEGIN{FS=":"}{print $1}'
# Output:
# [28/Sep/2010
# [28/Sep/2010
awk '{a+=$(NF-2); print "Total so far:", a}' logs.txt
# Output:
# Total so far: 200
# Total so far: 504
awk '{print $2}' logs.txt | awk 'BEGIN{FS=":"}{print $1}' | sed 's/\[//'
# Output:
# 28/Sep/2010
# 28/Sep/2010
07.46.199.184 [28/Sep/2010:04:08:20] "GET /robots.txt HTTP/1.1" 200 0 "msnbot"
123.125.71.19 [28/Sep/2010:04:20:11] "GET / HTTP/1.1" 304 - "Baiduspider"
# Reference
https://web.archive.org/web/20150906053501/http://gregable.com/2010/09/why-you-should-know-just-little-awk.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment