Wednesday, January 21, 2015

Searching Log files with AWK

I was digging through my notes and came across this little nugget. Say you have a log file and that log file entry has URL encoded values that you would prefer to see decoded. Here's the AWK I used to URL decode:

awk -F ^C '$4 ~ /SearchingFor/ {print $4}' access_log | awk '
{
    str = $0
    while (match(str,/%/)) {
      L = substr(str,1,RSTART-1) # chars to left of "%"
      M = substr(str,RSTART+1,2) # 2 chars to right of "%"
      R = substr(str,RSTART+3)   # chars to right of "%xx"
      str = sprintf("%s%c%s",L,hex2dec(M),R)
    }
    printf("%s\n",str)
    
}
function hex2dec(s,  num) {
    num = index("0123456789ABCDEF",toupper(substr(s,length(s)))) - 1
    sub(/.$/,"",s)
    return num + (length(s) ? 16*hex2dec(s) : 0)
}'

I found this on the web and I post it here so I don't loose it. I would love to give credit if I could remember where I got it.

No comments: