How can I pass variables from awk to a shell command?

前端 未结 5 1731
太阳男子
太阳男子 2020-12-01 04:14

I am trying to run a shell command from within awk for each line of a file, and the shell command needs one input argument. I tried to use system(), but it didn

5条回答
  •  無奈伤痛
    2020-12-01 04:54

    Or use the pipe | as in bash then retrive the output in a variable with awk's getline, like this

     zcat /var/log/fail2ban.log* | gawk  '/.*Ban.*/  {print $7};' | sort | uniq -c | sort | gawk '{ "geoiplookup " $2 "| cut -f2 -d: " | getline geoip; print $2 "\t\t" $1 " " geoip}'
    

    That line will print all the banned IPs from your server along with their origin (country) using the geoip-bin package.

    The last part of that one-liner is the one that affects us :

    gawk '{ "geoiplookup " $2 "| cut -f2 -d: " | getline geoip; print $2 "\t\t" $1 " " geoip}'
    

    It simply says : run the command "geoiplookup 182.193.192.4 | -f2 -d:" ($2 gets substituted as you may guess) and put the result of that command in geoip (the | getline geoip bit). Next, print something something and anything inside the geoip variable.

    The complete example and the results can be found here, an article I wrote.

提交回复
热议问题