Home > computers > linux > awk > awkcommand| About
How to retrieve the results of a command inside awk ?
The equivalent of bash's $(cmd arg)
in awk is :
"command arg" $awkvar " other command args if any" | getline somevar
You then have the result of the command in the somevar variable. Don't prefix the variable with $ to use it, just write somevar.
If this doesn't work, make sure you are using gawk and not mawk (debian ?) as there are subtle differences between the flavors of awk.
A Practical Example
print the origin of all the banned IP addresses on my mail server
root@messagerie-prod[10.10.10.19] /home/serveur # 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}' ... 54.76.38.42 1 US, United States 58.208.3.25 1 CN, China 58.214.18.235 1 CN, China 58.221.59.194 1 CN, China 58.243.51.66 1 CN, China 58.243.53.186 1 CN, China 59.124.246.2 1 TW, Taiwan 60.163.149.3 1 CN, China 60.163.150.205 1 CN, China 61.160.222.151 1 CN, China 61.187.235.80 1 CN, China 69.15.18.90 1 US, United States 76.72.163.76 1 US, United States 76.72.174.36 1 US, United States 84.55.64.211 1 SE, Sweden 91.108.176.183 1 GB, United Kingdom 92.125.34.223 1 RU, Russian Federation 93.107.34.251 1 IE, Ireland 96.91.42.136 1 US, United States 113.82.63.136 2 CN, China 116.5.164.170 2 CN, China 14.29.32.195 2 IP Address not found 146.71.110.19 2 US, United States 176.61.140.125 2 IP Address not found 182.72.187.153 2 IN, India 220.177.198.108 2 CN, China 222.64.216.242 2 CN, China 222.64.216.69 2 CN, China 222.64.217.85 2 CN, China 59.32.93.149 2 CN, China 66.147.31.180 2 US, United States 75.77.5.174 2 US, United States 148.251.110.58 3 DE, Germany 185.3.134.103 3 IP Address not found 101.87.209.183 4 IP Address not found 144.255.150.19 4 US, United States 58.55.136.176 7 CN, China root@messagerie-prod[10.10.10.19] /home/serveur #
contact : @ychaouche yacinechaouche at yahoocom